ASP. NET Core 1.0 Implementation of Mail Sending Function

  • 2021-08-12 02:29:20
  • OfStack

Prepare to migrate 1 project to asp. net core. Start with encapsulating class library. When encountering mail sending class, it is found that SMTP related class library is provided in asp. net core 1.0, so MailKit is found in 1 search on the Internet

Good thing 1 must try 1, let alone open source, the following is the code to achieve SMTP mail delivery:


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);
    
   }
  }

 }
} 

The above code is synchronous and asynchronous, and there is no problem
Note: 1 mailbox such as Tencent Enterprise Mail, 163, etc. can be sent successfully, but Alibaba Cloud Mail Push failed. If there is a master who can realize Alibaba Cloud Push Mail, please tell me 1, thank you very much!


Related articles: