需要用到的Nuget包
"MailKit": "1.8.1",
方法
/// <summary>
/// 发送邮件(支持Html发送,支持添加一个附件)
/// </summary>
/// <param name="subject">邮件标题</param>
/// <param name="email">收件人地址</param>
/// <param name="content">邮件内容</param>
/// <param name="filepath">文件的相对路径</param>
public static void SendEmail(string subject, string email,string content,string filepath=null)
{
var message = new MimeMessage();
//发信人
message.From.Add(new MailboxAddress("发信人姓名", "发信人邮箱"));
//收信人
message.To.Add(new MailboxAddress("", email));
//标题
message.Subject = subject;
//产生一个支持Html的TextPart
var body = new TextPart(TextFormat.Html)
{
Text = content
};
//先产生一个
var multipart = new Multipart("mixed");
//添加正文内容
multipart.Add(body);
if (!string.IsNullOrWhiteSpace(filepath))
{
//生产一个绝对路径
//filepath = "Upload//NewsPhoto//readme.txt";
var absolutePath = Path.Combine(_hostingEnv.WebRootPath, string.Format(filepath));
//附件
var attachment = new MimePart()
{
//读取文件(只能用绝对路径)
ContentObject = new ContentObject(File.OpenRead(absolutePath), ContentEncoding.Default),
ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Base64,
//文件名字
FileName = Path.GetFileName(absolutePath)
};
//添加附件
multipart.Add(attachment);
}
//正文内容
message.Body = multipart;
using (var client = new SmtpClient())
{
//连接到Smtp服务器
client.Connect("smtp服务器地址", 端口, false);
//登陆
client.Authenticate("账号", "密码");
//发送
client.Send(message);
//断开
client.Disconnect(true);
}
}
以上的这个方法可以发Html的文本并附带附件