1、web.config配置如下
1 <system.net>
2 <!--如果是第三方smtp服务器,需要指定userName 和 password,并根据host指定发件人邮件地址from
3 测试发现from值必须是userName值加上指定的smpt服务器才行,而且是必须指定的
4 如果是本机smtp服务器,只需指定defaultCredentials="true"即可-->
5 <mailSettings>
6 <smtp deliveryMethod="Network" from="XXXX@qq.com" >
7 <network host="smtp.qq.com" userName="XXXXXXX" password="XXXXXXX" />
8 </smtp>
9 </mailSettings>
10 </system.net>
2 <!--如果是第三方smtp服务器,需要指定userName 和 password,并根据host指定发件人邮件地址from
3 测试发现from值必须是userName值加上指定的smpt服务器才行,而且是必须指定的
4 如果是本机smtp服务器,只需指定defaultCredentials="true"即可-->
5 <mailSettings>
6 <smtp deliveryMethod="Network" from="XXXX@qq.com" >
7 <network host="smtp.qq.com" userName="XXXXXXX" password="XXXXXXX" />
8 </smtp>
9 </mailSettings>
10 </system.net>
2、后台代码
1 /// <summary>
2 /// 发送Email
3 /// </summary>
4 /// <param name="mailTo">收信人</param>
5 /// <param name="subject">主题</param>
6 /// <param name="body">内容</param>
7 /// <param name="isHtmlBody">内容是否使用html</param>
8 /// <returns>是否发送成功</returns>
9 public static bool SendEmail(string mailTo, string subject, string body, bool isHtmlBody)
10 {
11 using (MailMessage message = new MailMessage())
12 {
13 message.To.Add(new MailAddress(mailTo));
14
15 message.IsBodyHtml = isHtmlBody;
16
17 message.BodyEncoding = System.Text.Encoding.UTF8;
18
19 message.Subject = subject;
20
29 message.Body = body;
30
32 SmtpClient mailClient = new SmtpClient();
33
34 try
35 {
36 mailClient.Send(message);
37 }
38 catch (SmtpFailedRecipientsException ex)
39 {
40 for (int i = 0; i < ex.InnerExceptions.Length; i++)
41 {
42 SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
43 if (status == SmtpStatusCode.MailboxBusy || status == SmtpStatusCode.MailboxUnavailable)
44 {
45 System.Threading.Thread.Sleep(5000);
46 mailClient.Send(message);
47 }
48 }
49
50 }
51 catch (Exception ex)
52 {
53 return false;
54 }
55 return true;
56 }
57
58 }
2 /// 发送Email
3 /// </summary>
4 /// <param name="mailTo">收信人</param>
5 /// <param name="subject">主题</param>
6 /// <param name="body">内容</param>
7 /// <param name="isHtmlBody">内容是否使用html</param>
8 /// <returns>是否发送成功</returns>
9 public static bool SendEmail(string mailTo, string subject, string body, bool isHtmlBody)
10 {
11 using (MailMessage message = new MailMessage())
12 {
13 message.To.Add(new MailAddress(mailTo));
14
15 message.IsBodyHtml = isHtmlBody;
16
17 message.BodyEncoding = System.Text.Encoding.UTF8;
18
19 message.Subject = subject;
20
29 message.Body = body;
30
32 SmtpClient mailClient = new SmtpClient();
33
34 try
35 {
36 mailClient.Send(message);
37 }
38 catch (SmtpFailedRecipientsException ex)
39 {
40 for (int i = 0; i < ex.InnerExceptions.Length; i++)
41 {
42 SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
43 if (status == SmtpStatusCode.MailboxBusy || status == SmtpStatusCode.MailboxUnavailable)
44 {
45 System.Threading.Thread.Sleep(5000);
46 mailClient.Send(message);
47 }
48 }
49
50 }
51 catch (Exception ex)
52 {
53 return false;
54 }
55 return true;
56 }
57
58 }