准備將一些項目遷移到 asp.net core 先從封裝類庫入手,在遇到郵件發送類時發現在 asp.net core 1.0中並示提供SMTP相關類庫,於是網上一搜發現了MailKit
好東西一定要試一下,何況是開源,下面是代碼可實現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", "[email protected]")); 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("[email protected]", "******"); 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", "[email protected]")); 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("[email protected]", "******"); await client.SendAsync(emailMessage).ConfigureAwait(false); await client.DisconnectAsync(true).ConfigureAwait(false); } } } }
以上代碼同步異步都沒有問題
注:一般郵箱如騰訊企業郵、163等都可以發送成功,但阿裡雲郵件推送失敗,如果有高手可實現阿裡雲推送郵件請告訴我一下,非常感謝!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。