C# Mailkit 邮件发送

    public class MailHelper
    {
        static string MailFrom = ConfigurationManager.AppSettings["MailFrom"].ToString();
        static string MailFromAccount = ConfigurationManager.AppSettings["MailUserName"].ToString();
        static string MailPWD = ConfigurationManager.AppSettings["MailPassword"].ToString();
        static string DefaultMailTo = ConfigurationManager.AppSettings["DefaultMailTo"].ToString();
        static string SMTPServer = ConfigurationManager.AppSettings["MailSMTP"].ToString();
        static string SMTPServerPort = ConfigurationManager.AppSettings["MailPort"].ToString();

        #region send email by mailkit

        public static void SendEmail(string mailTo,string mailCC, bool isHtml,string subject,string body,string mailAttachement)
        {
            if (string.IsNullOrEmpty(mailTo.Trim()))
            {
                mailTo = DefaultMailTo;
            }

            if (string.IsNullOrEmpty(SMTPServerPort.Trim()))
            {
                SMTPServerPort = "25";
            }

            var message = new MimeMessage();
            List Tos = new List();
            List Ccs = new List();
            message.From.Add(new MailboxAddress(MailFrom, MailFromAccount));
            foreach (var to in mailTo.Trim().Split(';'))
            {
                if (!string.IsNullOrEmpty(to))
                {
                    Tos.Add(MailboxAddress.Parse(to));
                }
            }
            message.To.AddRange(Tos);

            if (!string.IsNullOrEmpty(mailCC))
            {
                foreach (var cc in mailCC.Trim().Split(';'))
                {
                    if (!string.IsNullOrEmpty(cc))
                    {
                        Ccs.Add(MailboxAddress.Parse(cc));
                    }
                }
            }

            if (Ccs.Count > 0)
            {
                message.Cc.AddRange(Ccs);
            }
            message.Subject = subject;

            var builder = new BodyBuilder();

            if (isHtml)
            {
                builder.HtmlBody = body;
            }
            else
            {
                builder.TextBody = body;
            }
            if (!string.IsNullOrEmpty(mailAttachement))
            {
                string[] attachementList = mailAttachement.Trim().Split(';').Distinct().ToArray();
                for (int i = 0; i < attachementList.Length; i++)
                {
                    if (attachementList[i].Length > 0)
                    {
                        builder.Attachments.Add(attachementList[i]);
                    }
                }
            }
            message.Body = builder.ToMessageBody();
            try
            {
                using (var smtp = new MailKit.Net.Smtp.SmtpClient())
                {
                    try
                    {
                        //MessageSent事件里可以通过args参数,获得服务器的响应信息,以便于记录Log
                        smtp.MessageSent += (sender, args) =>
                        {
                            //args.Response
                        };

                        smtp.ServerCertificateValidationCallback = (s, c, h, e) => true;
                        //var TokenSource = new CancellationTokenSource();

                        smtp.Connect(SMTPServer, Convert.ToInt32(SMTPServerPort), MailKit.Security.SecureSocketOptions.StartTls);
                        //smtp.Connect(SMTPServer, Convert.ToInt32(SMTPServerPort), false);
                        //smtp.Connect(SMTPServer, Convert.ToInt32(SMTPServerPort), MailKit.Security.SecureSocketOptions.StartTls, TokenSource.Token);

                        smtp.AuthenticationMechanisms.Remove("XOAUTH2");
                        smtp.Authenticate(MailFromAccount, MailPWD);
                        //smtp.Authenticate(MailFromAccount, MailPWD, TokenSource.Token);                    
                        smtp.Send(message);
                        smtp.Disconnect(true);
                    }
                    catch (Exception ex)
                    {
                        LoggerHelper.Error("Error: \n\t Error Message:" + ex.ToString());
                        LoggerHelper.Error("\t Error Stack Trace:" + ex.StackTrace);
                        LoggerHelper.Error("Add Mail To: " + mailTo);
                        LoggerHelper.Error("Add Mail CC: " + mailCC);
                        LoggerHelper.Error("Add Subject: " + subject);
                        LoggerHelper.Error("Add Body: " + body);
                    }
                    finally
                    {
                        if (smtp.IsConnected)
                        {
                            smtp.Disconnect(true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LoggerHelper.Error("Error: \n\t Error Message:" + ex.ToString());
                LoggerHelper.Error("\t Error Stack Trace:" + ex.StackTrace);
                LoggerHelper.Error("Add Mail To: " + mailTo);
                LoggerHelper.Error("Add Mail CC: " + mailCC);
                LoggerHelper.Error("Add Subject: " + subject);
                LoggerHelper.Error("Add Body: " + body);
            }
        }
        #endregion

    }

你可能感兴趣的:(c#,C#)