Example of implementation method for. NET to send mail

  • 2021-10-25 06:24:58
  • OfStack

Preface

This article mainly introduces the related contents of e-mail sent by. NET, and shares it for your reference and study. The following words are not much to say, let's take a look at the detailed introduction.

Note: You need to find the "POP3/SMTP service" and open it, and then generate the authorization code, which is the following login password.

For what the POP3/SMTP service is, you can refer to this article: https://www.ofstack.com/softjc/42323. html

You can refer to this article: https://www.ofstack.com/diannaojichu/520949. html

Sample code:


/// <summary>
 ///  Send Mail 
 /// </summary>
 /// <param name="to"> Recipients (multiple persons by ; Separate) </param>
 /// <param name="title"> Title </param>
 /// <param name="content"> Content </param>
 /// <param name="cc"> CC </param>
 /// <returns></returns>
 public string sendEmail(string to, string title, string content, string cc = "")
 {
  try
  {
   System.Net.Mail.MailMessage myMail = new System.Net.Mail.MailMessage();
   myMail.From = new System.Net.Mail.MailAddress("xxx@qq.com","xx Notice ", System.Text.Encoding.UTF8); // Sender's address, sender's name and code 
   string[] tos = to.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
   for (int i = 0; i < tos.Length; i++)
   {
    myMail.To.Add(new System.Net.Mail.MailAddress(tos[i]));
   }
   string[] ccs = cc.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
   for (int i = 0; i < ccs.Length; i++)
   {
    myMail.CC.Add(new System.Net.Mail.MailAddress(ccs[i]));
   }
   myMail.Subject = title;
   myMail.SubjectEncoding = Encoding.UTF8;
   myMail.Body = content;
   myMail.BodyEncoding = Encoding.UTF8;
   myMail.IsBodyHtml = true;
   System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
   smtp.Host = "smtp.qq.com";   smtp.EnableSsl = true;
   smtp.UseDefaultCredentials = false;
   smtp.Credentials = new System.Net.NetworkCredential("xxx@qq.com", "password");
   smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
   smtp.Send(myMail);
   return "";
  }
  catch (Exception ee)
  {
   return ee.ToString();
  }
 }

Summarize


Related articles: