ASP.NET Core 1.0實現郵件發送功能_實用技巧

來源:互聯網
上載者:User

準備將一些項目遷移到 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", "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);       }  } }} 

以上代碼同步非同步都沒有問題
 註:一般郵箱如騰訊企業郵、163等都可以發送成功,但阿里雲Direct Mail失敗,如果有高手可實現阿里雲推送郵件請告訴我一下,非常感謝!

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.