# 導包
首先我們需要匯入 MailKit NuGet包,NuGet安裝包命令在下方拓展介紹中,
# 參考命名空間
using MailKit.Net.Smtp; using MimeKit;
# 郵件發送幫助類
/// <summary> /// 發送郵件 /// </summary> /// <param name="Name">發件人名字</param> /// <param name="receive">接收郵箱</param> /// <param name="sender">發送郵箱</param> /// <param name="password">郵箱密碼</param> /// <param name="host">郵箱主機</param> /// <param name="port">郵箱埠</param> /// <param name="subject">郵件主題</param> /// <param name="body">郵件內容</param> /// <returns></returns> public async Task<bool> SendMailAsync(string Name, string receive, string sender, string password, string host, int port, string subject, string body) { try { # MimeMessage代表一封電子郵件的物件 var message = new MimeMessage(); # 添加發件人地址 Name 發件人名字 sender 發件人郵箱 message.From.Add(new MailboxAddress(Name, sender)); # 添加收件人地址 message.To.Add(new MailboxAddress("", receive)); # 設定郵件主題資訊 message.Subject = subject; # 設定郵件內容 var bodyBuilder = new BodyBuilder() { HtmlBody = body }; message.Body = bodyBuilder.ToMessageBody(); using (var client = new SmtpClient()) { // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS) client.ServerCertificateValidationCallback = (s, c, h, e) => true; // Note: since we don't have an OAuth2 token, disable // the XOAUTH2 authentication mechanism. client.AuthenticationMechanisms.Remove("XOAUTH2"); client.CheckCertificateRevocation = false; //client.SslProtocols = System.Security.Authentication.SslProtocols.Tls12; client.Connect(host, port, MailKit.Security.SecureSocketOptions.Auto); // Note: only needed if the SMTP server requires authentication client.Authenticate(sender, password); await client.SendAsync(message); client.Disconnect(true); return true; } } catch (Exception ex) { } return false; }
借助這一個簡單的郵件發送類我們就可以已經可以實作郵件發送功能了,
# 拓展(NuGet常用命令)
1、安裝指定版本:install-package <程式包名> -version <版本號>
2、更新包:Update-Package <程式包名>
3、重新安裝所有Nuget包(整個解決方案都會重新安裝)
update-package -reinstall
4、重新安裝指定專案所有Nuget包
update-package -project <專案名稱> -reinstall
5、正常卸載:uninstall-package <程式包名>
6、強制卸載:Uninstall-Package <程式包名> -Force
# 參考博文
https://blog.csdn.net/sD7O95O/article/details/89334103
https://www.cnblogs.com/qulianqing/p/7413640.html
https://www.cnblogs.com/savorboard/p/aspnetcore-email.html
https://www.cnblogs.com/daizhipeng/p/10955773.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/100091.html
標籤:.NET Core
