You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

281 lines
11 KiB

2 weeks ago
  1. using System;
  2. using System.Data;
  3. using System.Data.SqlClient;
  4. using System.Net;
  5. using System.Net.Mail;
  6. using System.Net.Mime;
  7. using System.Net.Security;
  8. using System.Security.Cryptography.X509Certificates;
  9. using System.Text;
  10. using System.Threading;
  11. namespace NFine.Code
  12. {
  13. public class MailHelper
  14. {
  15. /// <summary>
  16. /// 邮件服务器地址
  17. /// </summary>
  18. public string MailServer { get; set; }
  19. /// <summary>
  20. /// 用户名
  21. /// </summary>
  22. public string MailUserName { get; set; }
  23. /// <summary>
  24. /// 密码
  25. /// </summary>
  26. public string MailPassword { get; set; }
  27. /// <summary>
  28. /// 名称
  29. /// </summary>
  30. public string MailName { get; set; }
  31. private MailMessage message = new MailMessage();//申明邮件类
  32. /// <summary>
  33. /// 同步发送邮件
  34. /// </summary>
  35. /// <param name="to">收件人邮箱地址</param>
  36. /// <param name="subject">主题</param>
  37. /// <param name="body">内容</param>
  38. /// <param name="encoding">编码</param>
  39. /// <param name="isBodyHtml">是否Html</param>
  40. /// <param name="enableSsl">是否SSL加密连接</param>
  41. /// <returns>是否成功</returns>
  42. public bool Send(string to, string subject, string body, string encoding = "UTF-8", bool isBodyHtml = true, bool enableSsl = false)
  43. {
  44. try
  45. {
  46. MailMessage message = new MailMessage();
  47. // 接收人邮箱地址
  48. message.To.Add(new MailAddress(to));
  49. message.From = new MailAddress(MailUserName, MailName);
  50. message.BodyEncoding = Encoding.GetEncoding(encoding);
  51. message.Body = body;
  52. //GB2312
  53. message.SubjectEncoding = Encoding.GetEncoding(encoding);
  54. message.Subject = subject;
  55. message.IsBodyHtml = isBodyHtml;
  56. SmtpClient smtpclient = new SmtpClient(MailServer, 25);
  57. smtpclient.Credentials = new System.Net.NetworkCredential(MailUserName, MailPassword);
  58. //SSL连接
  59. smtpclient.EnableSsl = enableSsl;
  60. smtpclient.Send(message);
  61. return true;
  62. }
  63. catch (Exception)
  64. {
  65. throw;
  66. }
  67. }
  68. /// <summary>
  69. /// 异步发送邮件 独立线程
  70. /// </summary>
  71. /// <param name="to">邮件接收人</param>
  72. /// <param name="title">邮件标题</param>
  73. /// <param name="body">邮件内容</param>
  74. /// <param name="port">端口号</param>
  75. /// <returns></returns>
  76. public void SendByThread(string to, string title, string body, int port = 25)
  77. {
  78. new Thread(new ThreadStart(delegate()
  79. {
  80. try
  81. {
  82. SmtpClient smtp = new SmtpClient();
  83. //邮箱的smtp地址
  84. smtp.Host = MailServer;
  85. //端口号
  86. smtp.Port = port;
  87. //构建发件人的身份凭据类
  88. smtp.Credentials = new NetworkCredential(MailUserName, MailPassword);
  89. //构建消息类
  90. MailMessage objMailMessage = new MailMessage();
  91. //设置优先级
  92. objMailMessage.Priority = MailPriority.High;
  93. //消息发送人
  94. objMailMessage.From = new MailAddress(MailUserName, MailName, System.Text.Encoding.UTF8);
  95. //收件人
  96. objMailMessage.To.Add(to);
  97. //标题
  98. objMailMessage.Subject = title.Trim();
  99. //标题字符编码
  100. objMailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
  101. //正文
  102. objMailMessage.Body = body.Trim();
  103. objMailMessage.IsBodyHtml = true;
  104. //内容字符编码
  105. objMailMessage.BodyEncoding = System.Text.Encoding.UTF8;
  106. //发送
  107. smtp.Send(objMailMessage);
  108. }
  109. catch (Exception)
  110. {
  111. throw;
  112. }
  113. })).Start();
  114. }
  115. public static void SendEmail(string ConnectionString, string SendHost, int SendPort, string SendDisplayName, string SendAddress, string SendPassword, string TOAddress, string CCAddress, string Subject, bool IsBodyHtml, string Body, string POCode)
  116. {
  117. try
  118. {
  119. SmtpClient smtpClient = new SmtpClient
  120. {
  121. EnableSsl = true,
  122. UseDefaultCredentials = false,
  123. Host = SendHost,
  124. Port = SendPort,
  125. Credentials = new NetworkCredential(SendAddress, SendPassword)
  126. };
  127. MailMessage mailMessage = new MailMessage
  128. {
  129. Subject = Subject,
  130. SubjectEncoding = Encoding.GetEncoding("utf-8"),
  131. BodyEncoding = Encoding.GetEncoding("utf-8"),
  132. From = new MailAddress(SendAddress, SendDisplayName),
  133. IsBodyHtml = IsBodyHtml,
  134. Body = Body
  135. };
  136. string filePath = System.Web.HttpContext.Current.Server.MapPath("~\\File\\POReleaseFile\\" + POCode + ".pdf");
  137. AddAttachments(filePath);//添加附件
  138. string[] array = TOAddress.Split(new char[]
  139. {
  140. ','
  141. });
  142. string[] array2 = array;
  143. for (int i = 0; i < array2.Length; i++)
  144. {
  145. string text = array2[i];
  146. if (!string.IsNullOrEmpty(text))
  147. {
  148. mailMessage.To.Add(text);
  149. }
  150. }
  151. string[] array3 = CCAddress.Split(new char[]
  152. {
  153. ','
  154. });
  155. array2 = array3;
  156. for (int i = 0; i < array2.Length; i++)
  157. {
  158. string text2 = array2[i];
  159. if (!string.IsNullOrEmpty(text2))
  160. {
  161. mailMessage.CC.Add(text2);
  162. }
  163. }
  164. ServicePointManager.ServerCertificateValidationCallback = ((object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) => true);
  165. smtpClient.Send(mailMessage);
  166. InsertData(ConnectionString, SendHost, SendPort, SendDisplayName, SendAddress, SendPassword, TOAddress, CCAddress, Subject, IsBodyHtml, Body, "1", null);
  167. }
  168. catch (Exception ex)
  169. {
  170. InsertData(ConnectionString, SendHost, SendPort, SendDisplayName, SendAddress, SendPassword, TOAddress, CCAddress, Subject, IsBodyHtml, Body, "2", ex.Message);
  171. throw;
  172. }
  173. }
  174. public static void AddAttachments(string attachmentsPath)//这里的参数代表附件的绝对路径
  175. {
  176. try
  177. {
  178. string[] path = attachmentsPath.Split(';'); //以什么符号分隔可以自定义
  179. Attachment data;
  180. ContentDisposition disposition;
  181. for (int i = 0; i < path.Length; i++)
  182. {
  183. data = new Attachment(path[i], MediaTypeNames.Application.Octet);
  184. disposition = data.ContentDisposition;
  185. disposition.CreationDate = System.IO.File.GetCreationTime(path[i]);
  186. disposition.ModificationDate = System.IO.File.GetLastWriteTime(path[i]);
  187. disposition.ReadDate = System.IO.File.GetLastAccessTime(path[i]);
  188. }
  189. }
  190. catch (Exception ex)
  191. {
  192. Console.WriteLine(ex.ToString());
  193. }
  194. }
  195. private static void InsertData(string ConnectionString, string SendHost, int SendPort, string SendDisplayName, string SendAddress, string SendPassword, string TOAddress, string CCAddress, string Subject, bool IsBodyHtml, string Body, string Status, string Message)
  196. {
  197. try
  198. {
  199. try
  200. {
  201. string text = "INSERT INTO ICSSendMail(ID, SendHost, SendPort, SendDisplayName, SendAddress, \r\n SendPassword, TOAddress, CCAddress, Subject, IsBodyHtml, \r\n Body, Retry, Status, Message, MUSER, MUSERName, CreatTIME, ModifyTIME)\r\n VALUES(NEWID(),'{0}','{1}','{2}','{3}',\r\n '{4}','{5}','{6}','{7}','{8}',\r\n '{9}','0','{10}','{11}','','',GETDATE(),GETDATE())";
  202. text = string.Format(text, new object[]
  203. {
  204. SendHost,
  205. SendPort,
  206. SendDisplayName,
  207. SendAddress,
  208. SendPassword,
  209. TOAddress,
  210. CCAddress,
  211. Subject,
  212. IsBodyHtml,
  213. Body.Replace("'", "''"),
  214. Status,
  215. Message
  216. });
  217. ExecuteDate(ConnectionString, text);
  218. }
  219. catch (Exception ex)
  220. {
  221. throw ex;
  222. }
  223. }
  224. catch (Exception ex)
  225. {
  226. throw ex;
  227. }
  228. }
  229. private static void ExecuteDate(string conStr, string sql)
  230. {
  231. try
  232. {
  233. using (SqlConnection sqlConnection = new SqlConnection(conStr))
  234. {
  235. sqlConnection.Open();
  236. try
  237. {
  238. using (SqlTransaction sqlTransaction = sqlConnection.BeginTransaction())
  239. {
  240. using (SqlCommand sqlCommand = new SqlCommand())
  241. {
  242. sqlCommand.Connection = sqlConnection;
  243. sqlCommand.Transaction = sqlTransaction;
  244. sqlCommand.CommandText = sql;
  245. try
  246. {
  247. int num = sqlCommand.ExecuteNonQuery();
  248. sqlTransaction.Commit();
  249. }
  250. catch (Exception ex)
  251. {
  252. sqlTransaction.Rollback();
  253. throw ex;
  254. }
  255. }
  256. }
  257. }
  258. catch (Exception ex)
  259. {
  260. throw ex;
  261. }
  262. finally
  263. {
  264. if (sqlConnection.State == ConnectionState.Open)
  265. {
  266. sqlConnection.Close();
  267. }
  268. sqlConnection.Dispose();
  269. }
  270. }
  271. }
  272. catch (Exception ex)
  273. {
  274. throw ex;
  275. }
  276. }
  277. }
  278. }