ASP.Net core 使用mailkit发送邮件
程序员文章站
2023-12-28 10:35:04
...
首先安装mailkit
然后 控制器
using Microsoft.AspNetCore.Mvc;
using MimeKit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Threading.Tasks;
//SmtpClient smtpClient = System.Net.Mail.SmtpClient;
namespace emil.Controllers
{
public class Get : Controller
{
public void xx() {
//收件人邮箱
string mailName = "[email protected]";
//发送的标题
string title = "测试数据";
//发送的内容
string bobyText = "吃鸡丁拌面!";
// 邮件服务器smtp.qq.com表示qq邮箱服务器
string host = "smtp.qq.com";
// 发送端账号
string userName = "[email protected]";
// 发送端授权码,需要在邮箱获取授权码
string pwd = "vtwsxdesafdobjab";
MimeMessage message = new MimeMessage();
//发件人
message.From.Add(new MailboxAddress("T.Shiller", userName));
//收件人
message.To.Add(new MailboxAddress(title, mailName));
// message.To.Add(new MailboxAddress(title,mailName ));
//标题
message.Subject = title;
//正文内容,发送
message.Body = new BodyBuilder
{
HtmlBody = bobyText
}.ToMessageBody();
try
{
using (var client = new MailKit.Net.Smtp.SmtpClient())
{
//Smtp服务器
client.Connect(host, 587, false);
//登录,发送
client.Authenticate(userName, pwd);
client.Send(message);
//断开
client.Disconnect(true);
}
}
catch (Exception)
{
throw;
}
}
}
}