C# 发送邮件
likepoems

前言

本文简单的通过C#的SmtpClient实现发送邮件的功能。

实现

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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using System.Net.Mail;
using System.Net;

namespace Test
{
public class SendMail
{
private SmtpClient _emailClient;

public class UserInfo {
public string Email { get; set; } // 用户的邮箱
public string DisplayName { get; set; } // 用户的显示名称
}

/// <summary>
/// 发送邮件(邮件主题,邮件内容,接收人,抄送人,密送人,附件)
/// </summary>
public string SendMail(
string subject,
string body,
ICollection<UserInfo> tos,
ICollection<UserInfo>? ccs = null,
ICollection<UserInfo>? bccs = null,
ICollection<Attachment>? attachments = null)
{

// 设置smtp配置信息(以QQ邮箱为例)
string host = "smtp.qq.com"; // 邮件服务器
int port = 587; // 端口号
bool enableSsl = true; // 是否开启ssl
string username = "yourqqemail"; // 你的邮箱
string password = "yourpassword"; // 你的邮箱授权码
string senderAddress = "yourqqemail";// 你的邮箱
string senderDisplayName = "test"; // 发件人那里展示的名字

// 实例化smtp服务器
_emailClient = new SmtpClient
{
// 配置好服务器地址,端口和ssl,使用账密验证
Host = host,
Port = port,
EnableSsl = enableSsl,
Credentials = new NetworkCredential { UserName = username, Password = password }
};
MailMessage message = new()
{
// 设置邮件发送人
From = new MailAddress(senderAddress, senderDisplayName)
};

// 接收人
foreach (UserInfo user in tos)
{
message.To.Add(new MailAddress(user.Email, user.DisplayName));
}
// 抄送人
if (ccs != null)
{
foreach (UserInfo user in ccs)
{
message.CC.Add(new MailAddress(user.Email, user.DisplayName));
}
}
// 密送人
if (bccs != null)
{
foreach (UserInfo user in bccs)
{
message.Bcc.Add(new MailAddress(user.Email, user.DisplayName));
}
}
// 附件
if (attachments != null)
{
foreach (Attachment attachment in attachments)
{
message.Attachments.Add(attachment);
}
}
// 主题/内容/是否是html/默认优先级
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = true;
message.Priority = MailPriority.Normal;

try
{
_emailClient.Send(message);
return "邮件发送成功";
}
catch (Exception ex)
{
return ex.Message;
}
}
}
}

 评论
评论插件加载失败
正在加载评论插件