使用qq邮箱授权码发送邮件,避免密码泄露
引用发送邮件包
1
2
<package id="MailKit" version="2.7.0" targetFramework="net472" />
<package id="MimeKit" version="2.8.0" targetFramework="net472" />
发送邮件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
static async Task Main(string[] args)
{
var message = new MimeMessage
{
Subject = "标题",
Body = new BodyBuilder
{
HtmlBody = $"测试邮件,时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss}"
}.ToMessageBody()
};
await SendAsync(message);
Console.WriteLine("发送完成");
Console.ReadKey();
}
/// <summary>
/// 发送Email
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public static async Task SendAsync(MimeMessage message)
{
var host = "smtp.qq.com";
int port = 465;
bool UseSsl = true;
var fromUsername = "125880321@qq.com";
var fromPassword = "tfpcmxwtwaccbhga";
if (!message.From.Any())
{
message.From.Add(new MailboxAddress(fromUsername, fromUsername));
}
if (!message.To.Any())
{
var address = new MailboxAddress(fromUsername, fromUsername);
message.To.Add(address);
}
using (var client = new MailKit.Net.Smtp.SmtpClient
{
ServerCertificateValidationCallback = (s, c, h, e) => true
})
{
client.AuthenticationMechanisms.Remove("XOAUTH2");
await client.ConnectAsync(host, port, UseSsl);
await client.AuthenticateAsync(fromUsername, fromPassword);
await client.SendAsync(message);
await client.DisconnectAsync(true);
}
}
本文会经常更新,请阅读原文: https://dashenxian.github.io/post/%E4%BD%BF%E7%94%A8smtp%E5%8F%91%E9%80%81%E9%82%AE%E4%BB%B6 ,以避免陈旧错误知识的误导,同时有更好的阅读体验。
本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名 小神仙 (包含链接: https://dashenxian.github.io ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系 (125880321@qq.com) 。