背景
利用代碼發送郵件在工作中還是比較常見的,相信大家都用過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 });elsealternative.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.Noneclient.AuthenticationMechanisms.Remove("XOAUTH2");client.Authenticate(config.MailFromAccount, config.MailPassword);client.Send(emailMessage);client.Disconnect(true);}}}public class Config{public int Port { get; set; } = 25; //25public string Host { get; set; } //smtp.hantianwei.cnpublic bool IsHtml { get; set; } = true;public bool UseSsl { get; set; } = false;public string MailFromAccount { get; set; }//mail@hantianwei.cnpublic 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){}}
}