欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#帮助类:发送邮件

程序员文章站 2022-06-28 11:31:52
1 private static string IsOpenSendMail = ConfigurationManager.AppSettings["IsOpenSendMail"]; //是否启用异常消息发送邮箱功能 2 private static string SendUser=Configu... ......
 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         }