Implementation code of C sending mailbox

  • 2021-11-24 02:38:20
  • OfStack

I have never done the function of sending email before. Some time ago, the project needed it. After looking for a lot of posts, it was finally realized.

After that, I sorted out 1 and wrote 1 class. Pass information directly to the class, and you can send it.

It should also be noted here that POP3/SMTP service needs to be opened to send mailboxes, otherwise QQ mailboxes and Netease mailboxes will report errors. You don't need to open the received mailbox, and you will know the opening method under Baidu 1.


public static class EmailHelper
  {
    /// <summary>
    ///  Send Mail 
    /// </summary>
    /// <param name="subject"> Mail Subject </param>
    /// <param name="msg"> Mail content </param>
    /// <param name="filePath"> Attachment address, if no attachment is added, send it null Or ""</param>
    /// <param name="senderEmail"> Sender mailbox address </param>
    /// <param name="senderPwd"> Sender mailbox password </param>
    /// <param name="recipientEmail"> Recipient mailbox </param>
    public static void SendMail(string subject, string msg, string filePath, string senderEmail, string senderPwd, params string[] recipientEmail)
    {
      if (!CheckIsNotEmptyOrNull(subject, msg, senderEmail, senderPwd) || recipientEmail == null || recipientEmail.Length == 0)
      {
        throw new Exception(" Invalid information entered ");
      }
      try
      {
        string[] sendFromUser = senderEmail.Split('@');

        // Structure 1 A Email Adj. Message Object 
        MailMessage message = new MailMessage();

        // Determine smtp Server address. Instantiation 1 A Smtp Client 
        System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp." + sendFromUser[1]);

        // Constructing the Sender Address Object 
        message.From = new MailAddress(senderEmail, sendFromUser[0], Encoding.UTF8);

        // Construct a recipient address object 
        foreach (string userName in recipientEmail)
        {
          message.To.Add(new MailAddress(userName, userName.Split('@')[0], Encoding.UTF8));
        }

        if (!string.IsNullOrEmpty(filePath))
        {
          Attachment attach = new Attachment(filePath);
          // Get the information of the file 
          ContentDisposition disposition = attach.ContentDisposition;
          disposition.CreationDate = System.IO.File.GetCreationTime(filePath);
          disposition.ModificationDate = System.IO.File.GetLastWriteTime(filePath);
          disposition.ReadDate = System.IO.File.GetLastAccessTime(filePath);
          // Add an attachment to a message 
          message.Attachments.Add(attach);
        }

        // Add message subject and content 
        message.Subject = subject;
        message.SubjectEncoding = Encoding.UTF8;
        message.Body = msg;
        message.BodyEncoding = Encoding.UTF8;

        // Set up message information 
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        message.BodyEncoding = System.Text.Encoding.UTF8;
        message.IsBodyHtml = false;

        // If the server supports secure connections, set the secure connection to true . 
        //gmail,qq Support, 163 Not supported 
        switch (sendFromUser[1])
        {
          case "gmail.com":
          case "qq.com":
            client.EnableSsl = true;
            break;
          default:
            client.EnableSsl = false;
            break;
        }

        // Set the user name and password. 
        client.UseDefaultCredentials = false;
        // User login information 
        NetworkCredential myCredentials = new NetworkCredential(senderEmail, senderPwd);
        client.Credentials = myCredentials;
        // Send Mail 
        client.Send(message);
      }
      catch (Exception ex)
      {
        throw (ex);
      }
    }

    /// <summary>
    ///  Verify that all passed-in strings cannot be empty or null
    /// </summary>
    /// <param name="ps"> Parameter list </param>
    /// <returns> Neither is empty or null Return true Otherwise, return false</returns>
    public static bool CheckIsNotEmptyOrNull(params string[] ps)
    {
      if (ps != null)
      {
        foreach (string item in ps)
        {
          if (string.IsNullOrEmpty(item)) return false;
        }
        return true;
      }
      return false;
    }
  }

Call the method directly, pass the information that needs to be sent, and then you can send the mailbox.


Related articles: