什么是授权码,它又是如何设置?_QQ邮箱帮助中心
MailKit是流行且强大的.NET邮件处理框架
1、NET Core 管理 NuGet 程序包(N)...
MailKit
1、MailHelper.cs
using MimeKit;
using Config;
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Talk.Extensions;
namespace CoreLibrary
{
public static class MailHelper
{
public static async Task<bool> SendMail(string title, string content, MailRequest mailInfo = null)
{
if (mailInfo == null)
{
mailInfo = await FileConfig.GetMailInfoAsync();
if (mailInfo.MailPwd.IsNullOrWhiteSpace() ||
mailInfo.MailFrom.IsNullOrWhiteSpace() ||
mailInfo.MailHost.IsNullOrWhiteSpace())
{
throw new Exception("请先在 [/seting] 页面配置邮箱设置。");
}
}
var message = new MimeMessage();
message.From.Add(new MailboxAddress(mailInfo.MailFrom, mailInfo.MailFrom));
foreach (var mailTo in mailInfo.MailTo.Replace(";", ";").Replace(",", ";").Replace(",", ";").Split(';'))
{
message.To.Add(new MailboxAddress(mailTo, mailTo));
}
message.Subject = string.Format(title);
message.Body = new TextPart("html")
{
Text = content
};
using (var client = new MailKit.Net.Smtp.SmtpClient())
{
await client.ConnectAsync(mailInfo.MailHost, 465, true);
await client.AuthenticateAsync(mailInfo.MailFrom, mailInfo.MailPwd);
await client.SendAsync(message);
await client.DisconnectAsync(true);
}
return true;
}
public static async Task<bool> SendMail(string title, string content, string mailTo)
{
var info = await FileConfig.GetMailInfoAsync();
if (info.MailPwd.IsNullOrWhiteSpace() || info.MailFrom.IsNullOrWhiteSpace() || info.MailHost.IsNullOrWhiteSpace())
throw new Exception("请先在 [/seting] 页面配置邮箱设置。");
info.MailTo = mailTo;
return await SendMail(title, content, info);
}
}
}
2、FileConfig.cs
using Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Config
{
public static class FileConfig
{
private static string filePath = "File/Mail.txt";
private static MailRequest mailData = null;
public static async Task<MailRequest> GetMailInfoAsync()
{
if (mailData == null)
{
if (!System.IO.File.Exists(filePath)) return new MailRequest();
var mail = await System.IO.File.ReadAllTextAsync(filePath);
mailData = JsonConvert.DeserializeObject<MailRequest>(mail);
}
//深度复制,调用方修改。
return JsonConvert.DeserializeObject<MailRequest>(JsonConvert.SerializeObject(mailData));
}
public static async Task<bool> SaveMailInfoAsync(MailRequest MailRequest)
{
mailData = MailRequest;
await System.IO.File.WriteAllTextAsync(filePath, JsonConvert.SerializeObject(MailRequest));
return true;
}
}
}
3、MailRequest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Models
{
public class MailRequest
{
/// <summary>
/// 发件邮箱
/// </summary>
public string MailFrom { get; set; }
/// <summary>
/// 邮箱密码
/// </summary>
public string MailPwd { get; set; }
/// <summary>
/// 发件服务器
/// </summary>
public string MailHost { get; set; }
/// <summary>
/// 收件邮箱
/// </summary>
public string MailTo { get; set; }
}
public class SendMailRequest
{
public string Title { get; set; }
public string Content { get; set; }
public MailRequest MailInfo { get; set; } = null;
}
}
4、Constant.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Config
{
public class Constant
{
public const string MailTitle = "提示";
public const string MailContent = "MailContent";
public const string MailFrom = "123456789@qq.com";
public const string MailTo = "987654321@qq.com";
public const string MailPassword = "授权码,不是QQ邮箱密码";
public const string MailHost = "smtp.qq.com";
}
}
5、EmailController.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Config;
using CoreLibrary;
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class EmailController : ControllerBase
{
public EmailController()
{ }
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
[HttpPost]
public async Task<bool> SendMail([FromBody] SendMailRequest model)
{
model.MailInfo.MailFrom = Constant.MailFrom;
model.MailInfo.MailPwd = Constant.MailPassword;
model.MailInfo.MailHost = Constant.MailHost;
model.MailInfo.MailTo = Constant.MailTo;
return await MailHelper.SendMail(model.Title, model.Content, model.MailInfo);
}
}
}
* ========= NET Framework ========= 1、EmailHelper.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Linq;
using System.Net.Mail;
using System.Reflection;
using System.ServiceModel;
using System.Text;
namespace CoreLibrary
{
public class EmailHelper
{
/// <summary>
/// 邮件发送
/// </summary>
/// <param name="Mail_ad">收件人</param>
/// <param name="Mail_cc">抄送人</param>
/// <param name="title">标题</param>
/// <param name="msg">内容</param>
/// <param name="files">附件</param>
public void SendEmail(List<string> Mail_ad, List<string> Mail_cc, string title, string msg, List<string> files)
{
string FromAddress = ConfigurationManager.AppSettings["FromAddress"];
string Password = ConfigurationManager.AppSettings["FromPassword"];
string Sender = ConfigurationManager.AppSettings["FromSender"];
string SmtpHost = ConfigurationManager.AppSettings["SmtpHost"];
string SmtpPort = ConfigurationManager.AppSettings["SmtpPort"];
MailAddress from = new MailAddress(FromAddress, Sender);
SmtpClient client = new SmtpClient(SmtpHost, Convert.ToInt32(SmtpPort));
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(FromAddress, Password);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
if (Mail_ad != null && Mail_ad.Count > 0)
{
for (int i = 0; i < Mail_ad.Count; i++)
{
MailMessage message = new MailMessage();
message.From = from;
message.To.Add(Mail_ad[i].ToString());
if (Mail_cc != null && Mail_cc.Count > 0 && i == 0)
{
foreach (string item in Mail_cc)
message.CC.Add(item);
}
message.Subject = title;
message.Body = msg;
message.BodyEncoding = System.Text.Encoding.Default;
message.IsBodyHtml = true;
message.Attachments.Clear();
if (files != null && files.Count != 0)
{
decimal total = 0;
foreach (string item in files)
{
System.IO.FileInfo file = new System.IO.FileInfo(item);
total += file.Length / 1024;
}
if (total > 1024)
throw new FaultException("The file is too large.");
else
{
foreach (string item in files)
{
Attachment attach = new Attachment(item);
message.Attachments.Add(attach);
}
}
}
try
{
log4net.ILog logger = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
logger.Info("Entered SendEmail");
client.Send(message);
}
catch (Exception ex)
{
log4net.ILog logger = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
logger.Error(ex.ToString());
}
finally
{
message.Dispose();
}
}
}
else
throw new ArgumentNullException();
}
}
}
2、调用
public void SendEmailByMessage()
{
StringBuilder contents = new StringBuilder();
string title = string.Empty;
string address = string.Empty;
SendMail(title, contents.ToString(), address);
}
private void SendMail(string title, string content, string address)
{
EmailHelper eh = new EmailHelper();
List<string> files = new List<string>();
List<string> mail_ad = new List<string>();
List<string> mail_cc = null;
string cc = ConfigurationManager.AppSettings["ToCC"];
if (!string.IsNullOrEmpty(address))
mail_ad.Add(address);
if (!string.IsNullOrEmpty(cc))
mail_cc = cc.Split(new char[] { ',' }).Distinct().ToList();
eh.SendEmail(mail_ad, mail_cc, title, content, files);
}
=========邮箱设置========= 什么是授权码,它又是如何设置?_QQ邮箱帮助中心
1、邮箱设置 *
2、邮箱设置 - 账户
3、POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务
4、授权码
* * * * *
|