准备将一些项目迁移到 asp.net core 先从封装类库入手,在遇到邮件发送类时发现在 asp.net core 1.0中并示提供SMTP相关类库,于是网上一搜发现了MailKit
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);
}
}
}
}