源码地址:
https://github.com/jstedfast/MailKit
https://github.com/jstedfast/MimeKit
我要实现邮件发送功能,只需要以下步骤就可以
1、在.NET5项目中,引入MimeKit
2、封装一个发送类MailKitHelper,这里我用网易云的做测试
using System.Collections.Generic;
using C.Customization.Framework.Views;
using MimeKit;
namespace C.Customization.Framework.Comm
{
/// <summary>
/// 邮件发送辅助类
/// </summary>
public class MailKitHelper
{
const string mailFrom = "你的网易云邮箱@163.com";
const string mailFromAccount = "你的网易云邮箱@163.com";
const string mailPassword = "你的邮箱授权码";
/// <summary>
///发送邮件
/// </summary>
/// <param name="model">The model.</param>
/// <returns></returns>
public MessageInfo Send(SendEmailDto model)
{
if (string.IsNullOrWhiteSpace(model.SysName))
{
return new MessageInfo(false, "发件人称呼不能为空");
}
if (string.IsNullOrWhiteSpace(model.Subject))
{
return new MessageInfo(false, "主题不能为空");
}
if (model.ToMails == null || model.ToMails.Count < 1)
{
return new MessageInfo(false, "至少需要一个收件人");
}
if (string.IsNullOrWhiteSpace(model.HtmlBody))
{
return new MessageInfo(false, "信件内容不能为空");
}
MimeMessage message = new MimeMessage();
message.From.Add(new MailboxAddress(model.SysName, mailFrom));
model.ToMails.ForEach(x =>
{
message.To.Add(new MailboxAddress(x, x));
});
message.Subject = model.Subject;
BodyBuilder builder = new BodyBuilder();
if (model.Attas != null && model.Attas.Count > 0)
{
model.Attas.ForEach(x =>
{
builder.Attachments.Add(x);
});
}
builder.HtmlBody = model.HtmlBody;
message.Body = builder.ToMessageBody();
string retmsg = "";
using (var client = new MailKit.Net.Smtp.SmtpClient())
{
client.MessageSent += (s, a) =>
{
retmsg = a.Response;
};
client.Connect("smtp.163.com", 465, true);
client.Authenticate(mailFromAccount, mailPassword);
client.Send(message);
client.Disconnect(true);
}
return new MessageInfo(true, retmsg);
}
}
/// <summary>
/// 发送邮件入参
/// </summary>
public class SendEmailDto
{
/// <summary>
///系统名称 谁发邮件
/// </summary>
public string SysName { get; set; }
/// <summary>
///主题
/// </summary>
public string Subject { get; set; }
/// <summary>
/// 收件人邮箱集合
/// </summary>
public List<string> ToMails { get; set; }
/// <summary>
///附件文件地址 可为空
/// </summary>
public List<string> Attas { get; set; }
/// <summary>
///邮件内容
/// </summary>
public string HtmlBody { get; set; }
}
}3、按照入参对象传值即可。支持html和纯文本两种body,为了兼容性,我封装只保留了htmlbody。
川公网安备 51010702003150号
留下您的脚步
最近评论