-
-
Save Yuno-Liu/4709bb520f2588bd9acde2cc9f085634 to your computer and use it in GitHub Desktop.
MailKit-寄送Mail
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 建立Mail類別 | |
var message = new MimeMessage(); | |
// 添加寄件人(下兩種寫法均可) | |
//message.From.Add(MailboxAddress.Parse("From@gmail.com")); | |
// 可設定名稱 | |
message.To.Add(new MailboxAddress("FromName","From@gmail.com")); | |
// 添加收件人(下兩種寫法均可) | |
//message.From.Add(MailboxAddress.Parse("To@gmail.com")); | |
// 可設定名稱 | |
message.To.Add(new MailboxAddress("ToName","To@icloud.com")); | |
// 設定主旨標題 | |
message.Subject = "[測試通知]標題"; | |
// 建立內文類別 | |
var mailBody = new BodyBuilder(); | |
// 設定存文字內文 | |
mailBody.TextBody = "純文字"; | |
// 設定為HTML內文 | |
mailBody.HtmlBody = "<p>HTML文字</p> <br>"; | |
// 設定附件 | |
mailBody.Attachments.Add(@"C:\temp\testFile.txt"); | |
// 設定Mail內容 | |
message.Body = mailBody.ToMessageBody(); | |
// 建立SMTPClient | |
using (var client = new SmtpClient()) | |
{ | |
// 此範例已Gmail為例 | |
var host = "smtp.gmail.com"; | |
var port = 587; | |
// 預設為(Auto)也可以如有錯誤可透過明確定義來試試 | |
//client.Connect(host,port); | |
// 明確定義透過TLS(StartTls)連線建立連線服務 | |
client.Connect(host,port,SecureSocketOptions.StartTls); | |
// 透過指定用戶發送:用戶名、密碼驗證 | |
//client.Authenticate("uaerName","password"); | |
client.Authenticate("a91591536@gmail.com","o@ak4#4zEo6o4E&8*E"); | |
// 發送Mail | |
client.Send(message); | |
// 斷開連接(ture) | |
client.Disconnect(true); | |
Console.WriteLine("Done"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment