今天一天早,公司需要将之前的.net Core项目增加一个预处理机制,就是当程序出现异常后给我们的开发人员发送邮件,因为今天写些关于.netCore上发送邮件。
根据查阅资料发现在目前的Core1.0还没有直接发送邮件的类库,因此使用MailKit包来进行邮件的发送!
1.首先使用Nuget将 NETCore.MailKit 引用到程序中,然后调用该程序包进行发送,具体方法在下面!
#region 发送邮件
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="email"></param>
/// <param name="subject"></param>
/// <param name="message"></param>
public static void SendEmail(string email, string subject, string message)
{
var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress(emailAddressName, emailUserName));
string[] emailArray = email.Split(',');
foreach (var item in emailArray)
{
emailMessage.To.Add(new MailboxAddress(item));
}
emailMessage.Subject = subject;
emailMessage.Body = new TextPart("plain") { Text = message };
using (var client = new SmtpClient())
{
client.Connect(emailHost, , true);
client.Authenticate(emailUserName, emailPassword);
client.Send(emailMessage);
client.Disconnect(true);
}
}
/// <summary>
/// 异步发送邮件
/// </summary>
/// <param name="email"></param>
/// <param name="subject"></param>
/// <param name="message"></param>
/// <returns></returns>
public static async Task SendEmailAsync(string email, string subject, string message)
{
var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress(emailAddressName, emailUserName));
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(emailHost, , SecureSocketOptions.None).ConfigureAwait(false);
await client.AuthenticateAsync(emailUserName, emailPassword);
await client.SendAsync(emailMessage).ConfigureAwait(false);
await client.DisconnectAsync(true).ConfigureAwait(false);
}
}
以上就是调用MailKit 的发送方法,希望对大家有帮助!!如有问题请留言!!