c#帮助类:发送邮件

 1         private static string IsOpenSendMail = ConfigurationManager.AppSettings["IsOpenSendMail"]; //是否启用异常消息发送邮箱功能
 2         private static string SendUser=ConfigurationManager.AppSettings["MailUserName"];
 3         private static string SendPass= ConfigurationManager.AppSettings["MailPassword"];
 4         private static string ReceiveMail = ConfigurationManager.AppSettings["ReceiveMail"];
 5         private static string MailHost = ConfigurationManager.AppSettings["MailHost"]; //smtp.gmail.com
 6         private static string MailPort = ConfigurationManager.AppSettings["MailPort"]; //Gmail的smtp端口587
 7         /// <summary>
 8         /// 
 9         /// </summary>
10         /// <param name="mailName">标题</param>
11         /// <param name="body">内容</param>
12         /// <param name="encoding">编码</param>
13         /// <param name="isBodyHtml">是否Html</param>
14         /// <param name="enableSsl">是否SSL加密连接</param>
15         /// <returns>是否成功</returns>
16         /// <returns></returns>
17         public static void SendMail(string mailName, string body, string encoding = "UTF-8", bool isBodyHtml = true, bool enableSsl = true)
18         {
19             try
20             {
21                 if (!string.IsNullOrEmpty(IsOpenSendMail) && IsOpenSendMail=="开启")
22                 {
23                     MailMessage message = new MailMessage();
24                     message.To.Add(new MailAddress(ReceiveMail)); // 接收人邮箱地址
25                     message.From = new MailAddress(SendUser, mailName);
26                     message.BodyEncoding = Encoding.GetEncoding(encoding);
27                     message.Body = body;
28                     //GB2312
29                     message.SubjectEncoding = Encoding.GetEncoding(encoding);
30                     message.Subject = mailName;
31                     message.IsBodyHtml = isBodyHtml;
32 
33                     SmtpClient smtpclient = new SmtpClient(MailHost, Convert.ToInt32(MailPort)); //Gmail的smtp端口587
34                     smtpclient.Credentials = new System.Net.NetworkCredential(SendUser, SendPass);
35                     smtpclient.EnableSsl = enableSsl; //Gmail要求SSL连接
36                     smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network; //Gmail的发送方式是通过网络的方式,需要指定
37                     smtpclient.Send(message);
38                 }
39             }
40             catch (Exception ex)
41             {
42             }
43         }

 

posted @ 2019-01-04 22:39  Honker书生  阅读(504)  评论(0编辑  收藏  举报