C#QQ郵箱傳送訊息
阿新 • • 發佈:2020-07-22
QQ郵箱傳送訊息
在寫程式碼之前首先我們要獲取授權碼。
開啟我們的QQ郵箱=》點開設定=》點開賬戶=》我們就可以看到POP3/IMAP......服務
下面有各種服務,選擇你要開啟的服務,本人就開了第一了服務,完成後它會給你個授權碼,下面我們就會用到這個授權碼
首先我們在appsettings.json寫配置。
"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 //是否加密},
再寫個EmailConfig類放在Models資料夾中:
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 }); }