邮件发送封装方法

 1 /// <summary>
 2         /// 发送邮件
 3         /// </summary>
 4         /// <param name="subject">标题</param>
 5         /// <param name="body">内容</param>
 6         /// <param name="to">收件人</param>
 7         /// <param name="filePaths">附件路径</param>
 8         /// <param name="cc">抄送人</param>
 9         public static void SendMail(string subject, string body, List<string> to, List<string> filePaths = null, List<string> cc = null)
10         {
11             string host = ConfigurationManager.AppSettings["Smtp.Host"];
12             string port = ConfigurationManager.AppSettings["Smtp.Port"] ?? "25";
13             string account = ConfigurationManager.AppSettings["Smtp.Account"];
14             string password = ConfigurationManager.AppSettings["Smtp.Password"];
15             string from = ConfigurationManager.AppSettings["Smtp.From"];
16             string EnableSsl = ConfigurationManager.AppSettings["EnableSsl"] ?? "false";
17 
18             SmtpClient client = new SmtpClient(host, Convert.ToInt32(port));
19             client.DeliveryMethod = SmtpDeliveryMethod.Network;
20             client.Credentials = new NetworkCredential(account, password);
21 
22             client.EnableSsl = Convert.ToBoolean(EnableSsl);
23 
24             MailMessage mailMessage = new MailMessage() { From = new MailAddress(from) };
25             if (filePaths != null)
26             {
27                 foreach (var path in filePaths)
28                 {
29                     System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(path);
30                     mailMessage.Attachments.Add(attach);
31                 }
32             }
33 
34             mailMessage.Subject = subject;    //主题
35             mailMessage.Body = body;    //正文
36 
37             foreach (var addr in to)
38             {
39                 //收件人邮箱地址
40                 mailMessage.To.Add(new MailAddress(addr));
41             }
42 
43             if (cc != null)
44             {
45                 foreach (string addr in cc)
46                 {
47                     mailMessage.CC.Add(addr);
48                 }
49             }
50 
51             mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
52             mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
53             mailMessage.IsBodyHtml = true;
54 
55             client.Timeout = 10000;
56             client.Send(mailMessage);
57 
58         }

 

posted @ 2019-03-06 22:41  有意思7  阅读(247)  评论(0编辑  收藏  举报