配置类

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
namespace Configs
{
/// <summary>
/// 邮箱配置
/// </summary>
public class EMailConfig
{
/// <summary>
/// SMTP服务器
/// </summary>
/// <value></value>
public string SMTPService { get; set; }
/// <summary>
/// 端口
/// </summary>
/// <value></value>
public int Port { get; set; }
/// <summary>
/// 登录帐号
/// </summary>
/// <value></value>
public string UserName { get; set; }
/// <summary>
/// 登录密码
/// </summary>
/// <value></value>
public string Password { get; set; }
/// <summary>
/// 发件人
/// </summary>
/// <value></value>
public string FromEmail { get; set; }
public EMailConfig() { }

public EMailConfig(string smtpService, int port, string userName, string password, string fromEmail)
{
SMTPService = smtpService;
Port = port;
UserName = userName;
Password = password;
FromEmail = fromEmail;
}
}
}

方法

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
/// <summary>
/// 发送电子邮件
/// </summary>
/// <param name="config">配置</param>
/// <param name="toEmail">收件人</param>
/// <param name="subj">主题</param>
/// <param name="bodys">内容</param>
public static async Task SendMailAsync(EMailConfig config, string toMail, string subj, string bodys)
{
string host = config.SMTPService;//qq邮箱
int port = config.Port;
string from = config.FromEmail;
string to = toMail;
string userName = config.UserName;
string password = config.Password;

var message = new MimeMessage();
message.From.Add(new MailboxAddress(from));
message.To.AddRange(new MailboxAddress[] { new MailboxAddress(to) });
message.Subject = subj;
message.Body = new TextPart(TextFormat.Html)
{
Text = bodys
};
SmtpClient client = new SmtpClient();
await client.ConnectAsync(host, port, port == 465);//465端口是ssl端口
await client.AuthenticateAsync(userName, password);
await client.SendAsync(message);
await client.DisconnectAsync(true);
client.MessageSent += new EventHandler<MailKit.MessageSentEventArgs>((sender, e) =>
{
System.Console.WriteLine(e.Response);
});
}