1、Nuget安装Mailkit
2、appsettings.json 添加邮箱配置信息
"EmailInfo": {
"SmtpServer": "smtphz.qiye.163.com",
"Port": 465,
"Username": "你的邮箱账号",
"Password": "你的邮箱密码"
}
3、添加EmailInfoConst.cs
/// <summary>
/// 邮箱信息
/// </summary>
public class EmailInfoConst
{
/// <summary>
/// SMTP服务器地址
/// </summary>
public string SmtpServer { get; set; }
/// <summary>
/// 端口
/// </summary>
public int Port { get; set; }
/// <summary>
/// 用户名
/// </summary>
public string Username { get; set; }
/// <summary>
/// 密码
/// </summary>
public string Password { get; set; }
}
4、Program.cs 注入邮箱配置信息
builder.Services.AddSingleton(builder.Configuration.GetSection("EmailInfo").Get<EmailInfoConst>());
5、添加EmailHelper.cs 帮助类
/// <summary>
/// 发送邮箱
/// </summary>
[Serializable]
public static class EmailHelper
{
public static string SendEmail(EmailInfoConst emailInfo, string title, string receiveNmae, string receiveEmail, TextPart body)
{
try
{
MimeMessage message = new MimeMessage();
//发件人
message.From.Add(new MailboxAddress("测试发送用户", emailInfo.Username));
//收件人
message.To.Add(new MailboxAddress(receiveNmae, receiveEmail));
//标题
message.Subject = title;
生成一个支持Html的TextPart
//TextPart body = new TextPart(TextFormat.Html)
//{
// Text = "<h1>测试内容</h1> "
//};
//创建Multipart添加附件
Multipart multipart = new Multipart("mixed");
multipart.Add(body);
//正文
message.Body = multipart;
using (SmtpClient client = new SmtpClient())
{
//Smtp服务器
client.Connect(emailInfo.SmtpServer, emailInfo.Port, true);
if (client.IsConnected)
{
//登录
client.Authenticate(emailInfo.Username, emailInfo.Password);
//发送
string result = client.Send(message);
}
//断开
client.Disconnect(true);
return "发送邮件成功";
}
}
catch (Exception ex)
{
return "发送失败";
}
}
}
5、使用
1.构造函数注入EmailInfoConst
private readonly ILogger<HomeController> _logger;
private EmailInfoConst _emailInfo;
public HomeController(ILogger<HomeController> logger, EmailInfoConst emailInfo)
{
_logger = logger;
_emailInfo = emailInfo;
}
2.调用SendEmail函数
//生成一个支持Html的TextPart
TextPart body = new TextPart(TextFormat.Html)
{
Text = "<h1>测试邮件</h1> "
};
body.Text += $"<p> 请勿回复 </p>";
string sendResult = EmailHelper.SendEmail(_emailInfo, "邮箱测试", "接收人", "接收邮箱", body);