需要用到的Nuget包
"MailKit": "1.8.1",
方法
/// <summary> /// 發送郵件(支持Html發送,支持添加一個附件) /// </summary> /// <param name="subject">郵件標題</param> /// <param name="email">收件人地址</param> /// <param name="content">郵件內容</param> /// <param name="filepath">文件的相對路徑</param> public static void SendEmail(string subject, string email,string content,string filepath=null) { var message = new MimeMessage(); //發信人 message.From.Add(new MailboxAddress("發信人姓名", "發信人郵箱")); //收信人 message.To.Add(new MailboxAddress("", email)); //標題 message.Subject = subject; //產生一個支持Html的TextPart var body = new TextPart(TextFormat.Html) { Text = content }; //先產生一個 var multipart = new Multipart("mixed"); //添加正文內容 multipart.Add(body); if (!string.IsNullOrWhiteSpace(filepath)) { //生產一個絕對路徑 //filepath = "Upload//NewsPhoto//readme.txt"; var absolutePath = Path.Combine(_hostingEnv.WebRootPath, string.Format(filepath)); //附件 var attachment = new MimePart() { //讀取文件(只能用絕對路徑) ContentObject = new ContentObject(File.OpenRead(absolutePath), ContentEncoding.Default), ContentDisposition = new ContentDisposition(ContentDisposition.Attachment), ContentTransferEncoding = ContentEncoding.Base64, //文件名字 FileName = Path.GetFileName(absolutePath) }; //添加附件 multipart.Add(attachment); } //正文內容 message.Body = multipart; using (var client = new SmtpClient()) { //連接到Smtp服務器 client.Connect("smtp服務器地址", 端口, false); //登陸 client.Authenticate("賬號", "密碼"); //發送 client.Send(message); //斷開 client.Disconnect(true); } }
以上的這個方法可以發Html的文本並附帶附件