準備將一些項目遷移到 asp.net core 先從封裝類庫入手,在遇到郵件發送類時發如今 asp.net core 1.0中並示提供SMTP相關類庫,因而網上一搜發現了MailKitasp.net
好東西必定要試一下,況且是開源,下面是代碼可實現SMTP郵件發送:異步
using MailKit.Net.Smtp; using MailKit.Security; using MimeKit; using System.Threading.Tasks; namespace ConsoleApp1 { public class MailHelper { public static void Send(string email, string subject, string message) { var emailMessage = new MimeMessage(); emailMessage.From.Add(new MailboxAddress("tianwei blogs", "mail@hantianwei.cn")); emailMessage.To.Add(new MailboxAddress("mail", email)); emailMessage.Subject = subject; emailMessage.Body = new TextPart("plain") { Text = message }; using (var client = new SmtpClient()) { client.Connect("smtp.hantianwei.cn", 465, true); client.Authenticate("mail@hantianwei.cn", "******"); client.Send(emailMessage); client.Disconnect(true); } } public static async Task SendEmailAsync(string email, string subject, string message) { var emailMessage = new MimeMessage(); emailMessage.From.Add(new MailboxAddress("tianwei blogs", "mail@hantianwei.cn")); emailMessage.To.Add(new MailboxAddress("mail", email)); emailMessage.Subject = subject; emailMessage.Body = new TextPart("plain") { Text = message }; using (var client = new SmtpClient()) { await client.ConnectAsync("smtp.hantianwei.cn", 25, SecureSocketOptions.None).ConfigureAwait(false); await client.AuthenticateAsync("mail@hantianwei.cn", "******"); await client.SendAsync(emailMessage).ConfigureAwait(false); await client.DisconnectAsync(true).ConfigureAwait(false); } } } }
以上代碼同步異步都沒有問題async
注:通常郵箱如騰訊企業郵、163等均可以發送成功,但阿里雲郵件推送失敗,若是有高手可實現阿里雲推送郵件請告訴我一下,很是感謝!阿里雲