当前位置:网站首页>System.Net Email sending function

System.Net Email sending function

2020-11-10 16:04:26 JerryMouseLi

System.Net The email sending function stepped on the pit

1.EazyEmail Mail sending class library

Net The class library comes with mail sending function . The author of this class library , From the perspective of the use of secondary packaging ,nuget You can search for EazyEmail, When the container is injected, the configuration address of the mailbox server is obtained by delegation and the sending address is called directly send The method can .
Container injection code . The delegation defined here , Before sending each time, you can go to the database to get the mailbox configuration data and the sending account , I use it by myself Redis cache Access data , Because it may appear in batches like power failure , Need to send alarm email in bulk , So put Redis in , then Redis adopt rdb The function sets the policy of persisting every key change per second , No problem .

            services.AddEmailKit(() => 
           {
               EmailConfig emailConfig = new EmailConfig( );
               #region 163 Netease email sent 
                emailConfig.EmailSmtpAddress = "smtp.163.com";
                emailConfig.EmalHostPort = 587;
                emailConfig.SendEmailAccount = "13737732703@163.com";
                emailConfig.SendEmailPassWord = "******";
               #endregion

               #region qq  Mail delivery 
            //  emailConfig.EmailSmtpAddress = "smtp.qq.com";
            //  emailConfig.EmalHostPort = 587;
            //  emailConfig.SendEmailAccount = "87888397@qq.com";
            //  emailConfig.SendEmailPassWord = "*****";
               #endregion

               return emailConfig;
           });

Send code

 MailBox QqMailbox = new MailBox();

 QqMailbox.To = "87888397@qq.com";
 QqMailbox.Body = "qqfadsfa Mailbox test ";
 QqMailbox.Cc = "935467953@qq.com";
 QqMailbox.Subject = "qq Post fadfa Box test ";

 emailQueueService.Enqueue(QqMailbox); 

EazyEmail Built in blocking queue , As long as there's mail in the queue , If a thread is opened inside, it will continuously send , After sending, it will block , The execution right of the corresponding thread will return to the thread pool , Once there's mail going on , The thread automatically wakes up and continues to send mail . of EazyEmail If you need to introduce the use and design ideas, you can leave a message , We can start another article to explain , It has been uploaded to nuget, Search for EazyEmail To use the , Easy to use .

EazyEmail Class library source code github Address You can download it if you need it

2. Email authorization code and email password

Third party clients log in to the mail server to send mail , Receiving email has become extremely common , In some cases, it's embedded in the code to send email messages , Of course, it also includes the password to send the email , In recent two years, in order to improve the confidentiality of e-mails , Netease and qq The mailbox stipulates that the third-party client can only send mail by sending authorization code .

Netease send authorization code generation process :

Turn on the required email sending and receiving services

Mobile phone wechat scanning sends QR code

After the SMS is sent , Click I've sent Generate authorization code

This authorization code can be used directly as the sending password of the application .
qq E-mail authorization code generation process :

Steps to generate authorization code , Set up , The account goes down .

Click generate authorization code , Text messaging , I have sent , The corresponding authorization code can be generated .

remarks :qq E-mail has been using authorization code many years ago , And Netease , The author is in 15 The third-party client can be sent with a password , Now, of course, 15 The year setting is on pop/smtp, perhaps imap/smtp service , At that time did not generate the authorization code can still use the password to send , But after you have generated the authorization code, you can no longer send it with a password in Netease service provider , Third party can only send through authorization code . Even if you delete the authorization code , that pop/smtp, perhaps imap/smtp The service will shut down automatically .

3. Send mail by email password

Do you have this question at the same time , Can I send the email through the password of the mailbox ? The author has the following thinking , It is based on the convenience of users :

  1. The user has no concept of authorization code ;
  2. From a simple point of view , Direct account , Login password is the most convenient ;

In limine , I have no answer in my heart , But think of , The company's email password can be recorded foxmail, Then through this client to send and receive mail management mailbox . But I didn't succeed in sending email directly with code , Report failure . The failure code is as follows :

        static void Main(string[] args)
        {
            try 
            { 
               var client = new SmtpClient
               {
                   DeliveryMethod = SmtpDeliveryMethod.Network,
                   EnableSsl = true,
                   Host = "smtp.lead-it.cn",
                   Port = 465
               };
                   client.Credentials = new NetworkCredential("hekun@lead-it.cn", "*********");
                   MailMessage msg = new MailMessage("hekun@lead-it.cn", "87888397@qq.com", " test ", " Mailbox test ");  

               client.Send(msg);
               Console.WriteLine(" Email sent , Please remember to check !");
               Console.ReadKey();
            }
            catch (SmtpException ex)
            {
                Console.WriteLine(" Failed to send email :" + ex.Message);// Output error message 
            }
        }

4.Wireshark Caught analysis

When you encounter difficulties, you should face them ,foxmail What can be done , We can do the same . It only needs foxmail The process of sending e-mail , Analysis , And then send your own email , contrast , Find the difference and you can locate the problem .

I caught a little bag for a long time , No results , can't catch pop Follow SMTP Package of agreement .

After calm down to careful analysis is because the company mailbox server (163 Enterprise mailbox server , The administrator set up ssl) added ssl authentication .

The following can only be pasted with 163 The server does not encrypt the sending process and receiving process wireshark Grab the bag , Students who forget the password can retrieve the password by themselves , Only without encryption .
adopt pop Protocol to receive mail . Want to know IMAP Self capture of the agreement , The method is the same

smtp Send packets as follows , You can see that the user name and password are encrypted when sending

5. By password SSL Send successfully

Let's take a look at the sending success code

        static void Main(string[] args)
        {
            try 
            { 
               ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, errors) => true;
               var client = new SmtpClient
               {
                   DeliveryMethod = SmtpDeliveryMethod.Network,
                   EnableSsl = true,
                   Host = "smtp.lead-it.cn",
                   Port = 587
               };
                   client.Credentials = new NetworkCredential("hekun@lead-it.cn", "********");
                   MailMessage msg = new MailMessage("hekun@lead-it.cn", "87888397@qq.com", " test ", " Mailbox test ");  

               client.Send(msg);
               Console.WriteLine(" Email sent , Please remember to check !");
               Console.ReadKey();
            }
            catch (SmtpException ex)
            {
                Console.WriteLine(" Failed to send email :" + ex.Message);// Output error message 
            }
        }

5.1 Microsoft does not support 465 Of ssl

Through constant search , And debugging found .
oschina There is an article on

Microsoft is not supporting SSL over port 465 in c# 4/.NET 4.

Microsoft only supports SSL on 587 through "STARTTLS".

Microsoft doesn't support SSL The port is on 465, There may be 465 The port is occupied by other Microsoft Libraries . The general mail service will open more than one ssl port , such as 587. Of course, if it is the mail server built by the company itself, we need to pay attention to this pit , You only drive 465 ssl Port means never using Microsoft dad's mail Library .

5.2 ssl certificate

Solved the problem above 5.1, Have a 5.2 Questions as follows :

It may mean ssl The certificate is invalid .
stay stackoverflow We found the answer on :
the-remote-certificate-is-invalid

without ssl certificate , Add the following sentence directly , return true, Some information is not encrypted . Need to encrypt the reader to search to join ssl Document Certificate .

       ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, errors) => true;

Corporate email ( Enterprise class Netease mailbox allows third-party clients not to pass the authorization code ) Send email to... Via email password qq mailbox ,qq Email received by email is as follows :

thus , Problem solving .

6 Summary

About being able to send email with authorization code or password , It's not up to us to decide , It is determined by the interface provided by the mail service provider , He has no authorization code generation function , Naturally, it can only be sent by password ; He ( NetEase mail box ,QQ mailbox ) It is stipulated that only authorization codes can be used to send , That's what we can do ; If it's an authorization code, you can use both , Readers make their own decisions in terms of safety and convenience .

版权声明
本文为[JerryMouseLi]所创,转载请带上原文链接,感谢