1、安裝Nuget包MailKit,引用命名空間。 using MailKit.Net.Smtp; using MimeKit; 註意:引用MailKit對應最新版本 2、定義收發地址和標題 MimeMessage message = new MimeMessage(); MailboxAddres ...
1、安裝Nuget包MailKit,引用命名空間。
using MailKit.Net.Smtp; using MimeKit;
註意:引用MailKit對應最新版本
2、定義收發地址和標題
MimeMessage message = new MimeMessage(); MailboxAddress from = new MailboxAddress("Admin","[email protected]"); message.From.Add(from); MailboxAddress to = new MailboxAddress("User", "[email protected]"); message.To.Add(to); message.Subject = "This is email subject";
註意:Admin,User分別對應發送接收郵箱首碼
3、編寫內容
BodyBuilder bodyBuilder = new BodyBuilder(); bodyBuilder.HtmlBody = "<h1>Hello World!</h1>"; bodyBuilder.TextBody = "Hello World!";
message.Body = bodyBuilder.ToMessageBody();
註意:也可以自定義模板,插入圖片等等。
4、連接SMTP伺服器發送郵件
SmtpClient client = new SmtpClient();
client.Connect("smtp_address_here", port_here, true); //例如:smtp.exmail.qq.com,465
client.Authenticate("[email protected]", "password"); //發送郵件的賬戶密碼
client.Send(message);
client.Disconnect(true);
client.Dispose();