準(zhǔn)備將一些項(xiàng)目遷移到 asp.net core 先從封裝類(lèi)庫(kù)入手,在遇到郵件發(fā)送類(lèi)時(shí)發(fā)現(xiàn)在 asp.net core 1.0中并示提供SMTP相關(guān)類(lèi)庫(kù),于是網(wǎng)上一搜發(fā)現(xiàn)了MailKit
好東西一定要試一下,何況是開(kāi)源,下面是代碼可實(shí)現(xiàn)SMTP郵件發(fā)送:
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); } } } }
以上代碼同步異步都沒(méi)有問(wèn)題
注:一般郵箱如騰訊企業(yè)郵、163等都可以發(fā)送成功,但阿里云郵件推送失敗,如果有高手可實(shí)現(xiàn)阿里云推送郵件請(qǐng)告訴我一下,非常感謝!
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com