.NET CORE 下收发邮件之 MAILKIT

Posted dotNET跨平台

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了.NET CORE 下收发邮件之 MAILKIT相关的知识,希望对你有一定的参考价值。

背景

利用代码发送邮件在工作中还是比较常见的,相信大家都用过SmtpClient来处理发送邮件的操作,不过这个类以及被标记已过时,所以介绍一个微软推荐的库MailKit来处理。

MailKit开源地址:https://github.com/jstedfast/MailKit

需要邮件功能

1、服务提供方:需提供邮件收发客户端或Web服务。如:QQ邮箱、GMail邮箱、126、163等知名邮件服务提供商。注:如果你使用的第三方不知名邮件服务商提供的邮件收发服务,通过其发出的邮件,可能会被其他知名邮件服务提供商的STMP服务器视为是"恶意邮件或垃圾邮件"!

2、消息推送:消息推送方

3、App:某些网站会员的注册功能或者功能激活功能。

协议

1、SMTP(Simple Mail Transfer Protocol)   ---简单邮件传输协议

2、POP3(Post Office Protocol -Version3)   ---邮局协议第三个版本

代码实现

1、新建项目 引用 MailKit

using MailKit.Net.Smtp;using MimeKit;

2、指定发件人、收件人、附件等信息

[HttpPost]
        [Route("sendmail")]
        public bool Sendmail(SendmailDto model)
        
            string mailTo = model.mail;
            string title = model.title;
            string requestId = Guid.NewGuid().ToString("N");
            string path = WriteFilepath(requestId, title + ".html", model.str);
            string docpath = path.Replace(".html", ".docx");
            try
            
                string applicationRoot = AppContext.BaseDirectory;
                var provider = new PhysicalFileProvider(applicationRoot);

                string apath = @"C:/www/fengnan";
                // string apath = @"C:/net6.0";

                var filePath =
                 //applicationRoot +
                 apath + $"/Template/fldoc/" + requestId + "/";
                var filePath2 =
               //applicationRoot +
               apath + $"/Template/fldoc/" + requestId + "/"
                  + title + ".html";

                ecmd("soffice --headless --convert-to docx:\\"Office Open XML Text\\" " + filePath2 + " --outdir " + filePath);

                //   string docpath = path.Replace(".html", ".docx");
            
            catch (Exception ex)
            
                _logger.Error(ex);
            

            // string mailFrom = "xxxx@qq.com";
            string mailFrom = "xxx@xx.net";

            //   mailTo = "xx@xxx.com";
            string Text = "内容见附件,请查收<br/> 感谢";
            string mailFromAccount = "xxx@qq.com";
            string mailPassword = "xxxx";

            string mailFromAccount = "xxx@xx.net";
            string mailPassword = "xxxx@";

            var contentRoot = Directory.GetCurrentDirectory();
            var webRoot = Path.Combine(contentRoot, "wwwroot");
            ///  string path = Path.Combine(webRoot, "Images/icc.png");

            //  string path = @"D:\\xxxx知.html";

            //  string Text = @"Hey Chandler,

            //I just wanted to let you know that Monica and I were going to go play some paintball, you in?

            //-- Joey";

            Config eConfig = new Config
                            From = new MailAddress("xxxx", mailFrom),
                //  Host = "smtp.qq.com",                Host = "smtp.exmail.qq.com",                MailFromAccount = mailFromAccount,                MailPassword = mailPassword,
                // Port = 587,                Port = 465,                UseSsl = true,                IsHtml = true
            ;

            List<MailAddress> tos = new List<MailAddress>();
            tos.Add(new MailAddress("", mailTo));

            List<string> flist = new List<string>();

            if (System.IO.File.Exists(docpath))
            
                flist.Add(docpath);
                //docpath
            
            else
            
                flist.Add(path);
            

            Mailhelper.SendEmail(eConfig, tos, title, Text, flist.ToArray());

            return true;
        

3、发邮件帮助类

using MimeKit;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace DFTech.Service.Filters

    /// <summary>
    /// 发邮件
    /// </summary>
    public class Mailhelper
    
        /// <summary>
        /// 发邮件
        /// </summary>
        /// <param name="config"></param>
        /// <param name="tos"></param>
        /// <param name="subject"></param>
        /// <param name="message"></param>
        /// <param name="attachments"></param>
        /// <returns></returns>
        public  static void SendEmail(Config config, List<MailAddress> tos, string subject, string message, params string[] attachments)
        
            var emailMessage = new MimeMessage();

            emailMessage.From.Add((MailboxAddress)config.From);
            foreach (var to in tos)
                emailMessage.To.Add(to as MailAddress);

            emailMessage.Subject = subject;

            var alternative = new Multipart("alternative");
            if (config.IsHtml)
                alternative.Add(new TextPart("html")  Text = message );
            else
                alternative.Add(new TextPart("plain")  Text = message );

            if (attachments != null)
            
                foreach (string f in attachments)
                
                    var attachment = new MimePart()//("image", "png")
                    
                        ContentObject = new ContentObject(File.OpenRead(f), ContentEncoding.Default),
                        ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName = Path.GetFileName(f)
                    ;
                    alternative.Add(attachment);
                
            
            emailMessage.Body = alternative;

            using (var client = new SmtpClient())
            
                 client.Connect(config.Host, config.Port, config.UseSsl);// SecureSocketOptions.None
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                 client.Authenticate(config.MailFromAccount, config.MailPassword);
                 client.Send(emailMessage);
                 client.Disconnect(true);
            
        
    

    public class Config
    
        public int Port  get; set;  = 25; //25
        public string Host  get; set;  //smtp.hantianwei.cn

        public bool IsHtml  get; set;  = true;

        public bool UseSsl  get; set;  = false;

        public string MailFromAccount  get; set; //mail@hantianwei.cn
        public string MailPassword  get; set; 

        public MailAddress From  get; set; 
    

    /// <summary>
    ///
    /// </summary>
    public class MailAddress : MailboxAddress
    
        public MailAddress(string name, string address) : base(name, address)
        
        

        public MailAddress(Encoding encoding, string name, string address) : base(encoding, name, address)
        
        
    

以上是关于.NET CORE 下收发邮件之 MAILKIT的主要内容,如果未能解决你的问题,请参考以下文章

愚公系列2023年02月 .NET CORE工具案例-使用MailKit使用SMTP协议进行邮件发送

愚公系列2023年02月 .NET CORE工具案例-使用MailKit使用POP3协议进行邮件读取

MailKit和MimeKit 收发邮件

如何在 ASP.NET Core 中发送邮件

.Net Core 5 web api 使用 mimekit 和 mailkit 的电子邮件附件

使用 .NET core 2.2 中的 MailKit SMTP 客户端通过 Gmail SMTP 发送邮件对我不起作用