"QQEmailConfig": {
//发件人 "From": { "email": "自己的QQ邮箱", "displayname": "tomorrow得到系统通知"//显示的名称 }, "AuthorizationCode": "自己的授权码",
//收件人 "Addressee": [ { "email": "张三的QQ邮箱", "displayname": "张三" }, { "email": "李四的QQ邮箱", "displayname": "李四" } ], "Subject": "tomorrow的系统通知123",//统一标题 "Host": "smtp.qq.com",//主机 "Port": 587,//端口 "EnableSsl": true //是否加密 },
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; } }
最后就是写代码的时间了:
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>没有变";
//内容是否为html渲染 mail.IsBodyHtml = true;
//标题编码 mail.SubjectEncoding = Encoding.UTF8;
//内容编码 mail.BodyEncoding = Encoding.UTF8;
//附件 mail.Attachments.Add(new Attachment(@"C:\Users\Administrator\Pictures\Saved Pictures\timg.jpg"));
//smtp客户端 using(SmtpClient client=new SmtpClient()) {
//主机 client.Host = emailConfig.Host;
//端口 client.Port = emailConfig.Port;
//凭证(发件人email 授权) client.Credentials = new NetworkCredential(emailConfig.From.email, emailConfig.AuthorizationCode);
//是否加密 client.EnableSsl = emailConfig.EnableSsl;
//发送邮件 await client.SendMailAsync(mail); } }; return new JsonResult(new { Code=200, message="邮件完成,请注意查收", data = emailConfig.Addressee }); }