using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using SendEmailDemo.Models; using System.Net; using System.Net.Mail; using System.Text; using System.Threading.Tasks; namespace SendEmailDemo.Controllers { [Route("[controller]/[action]")] [ApiController] public class HomeController : ControllerBase { private readonly IConfiguration _configuration; public HomeController(IConfiguration configuration) { _configuration = configuration; } public async Task<IActionResult> SendQQEmail() { //读取配置文件 EmailConfig emailConfig = _configuration.GetSection("QQEmailConfig").Get<EmailConfig>(); //实例化对象 using (MailMessage mail = new MailMessage()) { //发件人 mail.From = new MailAddress(emailConfig.From.email, emailConfig.From.displayname); //收件人 foreach (var item in emailConfig.Addressee) { mail.To.Add(new MailAddress(item.email, item.displayname)); } //标题 mail.Subject = emailConfig.Subject; //内容 mail.Body = "<b>财报显示</b>,保利地产2019年上半年净利润同比增长53.28%,2018年上半年净利润同比增长14.94%,2017年净利润同比增长13.92%。由此可见,保利地产今年上半年净利润增速创下三年来新低。"; //内容是否为 html 渲染 mail.IsBodyHtml = true; //标题编码 mail.SubjectEncoding = Encoding.UTF8; //内容编码 mail.BodyEncoding = Encoding.UTF8; //附件 mail.Attachments.Add(new Attachment(@"D:\Music\林俊杰 - 曹操.m4a")); //smtp客户端 using (SmtpClient client = new SmtpClient()) { //主机 client.Host = emailConfig.Host; //端口 client.Port = emailConfig.Port; //是否为加密 client.EnableSsl = emailConfig.EnableSsl; //凭证(发件人email、 授权码) client.Credentials = new NetworkCredential(emailConfig.From.email, emailConfig.AuthorizationCode); //发送邮件 await client.SendMailAsync(mail); } return new JsonResult(new { code = 200, message = "邮件已发送请注意查收", data = emailConfig.Addressee }); } } } }
//配置文件实体类
public class EmailConfig { public class Config { public string email { get; set; } public string displayname { get; set; } } public Config From { get; set; } public Config[] Addressee { get; set; } public string AuthorizationCode { get; set; } public string Subject { get; set; } public string Host { get; set; } public int Port { get; set; } public bool EnableSsl { get; set; } }
//配置文件
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "QQEmailConfig": { "From": { //发件人 "email": "123456789@qq.com", //邮件 "displayname": "tomorrow得到系统通知" //显示名称 }, "AuthorizationCode": "************", //授权码 "Addressee": [ //收件人 { "email": "147258369@qq.com", "displayname": "张三" }, { "email": "963852741@qq.com", "displayname": "李四" } ], "Subject": "tomorrow的系统通知", //统一标题 "Host": "smtp.qq.com", //主机 "Port": 587, //端口 "EnableSsl": true //是否加密 }, "AllowedHosts": "*" }
获取授权码
发送短信,后点击 “我已发送”
附件预览