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.

307 lines
11 KiB

  1. using CounsellorBL.BLStructure;
  2. using log4net;
  3. using MonumentDefine;
  4. using OT.COM.ArsenalDB;
  5. using OT.COM.LogisticsUtil;
  6. using SoldierData.EnterprizeV4;
  7. using System;
  8. using System.Collections.Concurrent;
  9. using System.Collections.Generic;
  10. using System.Globalization;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Net;
  14. using System.Net.Mail;
  15. using System.Net.Mime;
  16. using System.Text;
  17. namespace CounsellorBL.Helper
  18. {
  19. /// <summary>
  20. /// 類別名稱:Mailer
  21. /// 類別說明:
  22. /// 起始作者:
  23. /// 起始日期:
  24. /// 最新修改人:
  25. /// 最新修改日:
  26. /// </summary>
  27. public partial class MailHelper
  28. {
  29. /// <summary>
  30. /// 類別成員、類別屬性說明:_inst
  31. /// </summary>
  32. private ILog _inst = null;
  33. protected ILog Logger
  34. {
  35. get
  36. {
  37. if (_inst == null)
  38. {
  39. _inst = LogManager.GetLogger(this.GetType());
  40. }
  41. return _inst;
  42. }
  43. }
  44. /// <summary>
  45. /// 類別成員、類別屬性說明:SMTP
  46. /// </summary>
  47. public string SMTP { get; set; }
  48. /// <summary>
  49. /// 類別成員、類別屬性說明:FromAddress
  50. /// </summary>
  51. public string FromAddress { get; set; }
  52. /// <summary>
  53. /// 類別成員、類別屬性說明:Account
  54. /// </summary>
  55. public string Account { get; set; }
  56. /// <summary>
  57. /// 類別成員、類別屬性說明:EnterCode
  58. /// </summary>
  59. public string EnterCode { get; set; }
  60. /// <summary>
  61. /// 類別成員、類別屬性說明:Name
  62. /// </summary>
  63. public string Name { get; set; }
  64. /// <summary>
  65. /// 類別成員、類別屬性說明:Port
  66. /// </summary>
  67. public int Port { get; set; }
  68. /// <summary>
  69. /// 類別成員、類別屬性說明:ErrorMessage
  70. /// </summary>
  71. public string ErrorMessage { get; set; }
  72. /// <summary>
  73. /// 類別成員、類別屬性說明:SSL
  74. /// </summary>
  75. public bool SSL { get; set; }
  76. public string UseDefaultCredentials { get; set; }
  77. /// <summary>
  78. /// 類別成員、類別屬性說明:MyEncoding
  79. /// </summary>
  80. public Encoding MyEncoding { get; set; }
  81. /// <summary>
  82. /// 類別成員、類別屬性說明:建構子
  83. /// </summary>
  84. public MailHelper()
  85. {
  86. MyEncoding = Encoding.GetEncoding("UTF-8");
  87. ConcurrentDictionary<string, string> dicSetting = CustomizeDBMgr.SettingData;
  88. string sUseSSL = dicSetting.ContainsKey("USESSL") ? dicSetting["USESSL"] : null;
  89. SMTP = dicSetting.ContainsKey("SMTPURL") ? dicSetting["SMTPURL"] : null;
  90. FromAddress = dicSetting.ContainsKey("MAILOWNERADDRESS") ? dicSetting["MAILOWNERADDRESS"] : null;
  91. Account = dicSetting.ContainsKey("MAILACCOUNT") ? dicSetting["MAILACCOUNT"] : null;
  92. EnterCode = dicSetting.ContainsKey("MAILPASS") ? dicSetting["MAILPASS"] : null;
  93. Name = dicSetting.ContainsKey("MAILACCOUNT") ? dicSetting["MAILACCOUNT"] : null;
  94. Port = dicSetting.ContainsKey("MAILPORT") ? Convert.ToInt32(dicSetting["MAILPORT"], CultureInfo.CurrentCulture) : 587;
  95. SSL = (sUseSSL?.ToLower(CultureInfo.CurrentCulture).StartsWith("y", StringComparison.OrdinalIgnoreCase)).Value;
  96. MyEncoding = Encoding.GetEncoding("UTF-8");
  97. UseDefaultCredentials = dicSetting.ContainsKey("USEDEFAULTCREDENTIALS") ? dicSetting["USEDEFAULTCREDENTIALS"] : null;
  98. }
  99. /// <summary>
  100. /// 函式名稱:Send
  101. /// 函式說明:寄信動作
  102. /// 起始作者:
  103. /// 起始日期:
  104. /// 最新修改人:
  105. /// 最新修改日:
  106. /// </summary>
  107. /// <param name="strSubject">主旨</param>
  108. /// <param name="strBody">信件內容</param>
  109. /// <param name="arrayStrToAddressAndName">收件者</param>
  110. /// <param name="bHTML"></param>
  111. /// <param name="arrayStrAttached">附件</param>
  112. /// <param name="arrayStrCCAddressAndName">CC</param>
  113. /// <param name="arrayStrBCCAddressAndName">BCC</param>
  114. /// <returns></returns>
  115. public string Send(string i_strSubject, string strBody, List<MailAccountInfo> arrayStrToAddressAndName,
  116. bool bHTML = true,
  117. List<MailAccountInfo> arrayStrCCAddressAndName = null,
  118. List<MailAccountInfo> arrayStrBCCAddressAndName = null,
  119. List<string> i_lAttachPaths = null,
  120. [System.Runtime.CompilerServices.CallerLineNumber] int i_nCodeLine = 0,
  121. [System.Runtime.CompilerServices.CallerMemberName] string i_sMemberName = "",
  122. [System.Runtime.CompilerServices.CallerFilePath] string i_sSourcePath = ""
  123. )
  124. {
  125. string sMsg = null;
  126. string strSubject = i_strSubject;
  127. Logger.Debug(string.Format(CultureInfo.CurrentCulture, "MailHelper Send Start, Title{0}", strSubject));
  128. try
  129. {
  130. System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage();
  131. if (!string.IsNullOrWhiteSpace(this.FromAddress))
  132. {
  133. mm.Sender = new System.Net.Mail.MailAddress(string.Format(CultureInfo.CurrentCulture, "{1}<{0}>", this.FromAddress, this.Name));
  134. mm.From = new System.Net.Mail.MailAddress(string.Format(CultureInfo.CurrentCulture, "{1}<{0}>", this.FromAddress, this.Name));
  135. }
  136. mm.Subject = strSubject;
  137. mm.IsBodyHtml = bHTML;
  138. mm.Body = strBody;
  139. mm.BodyEncoding = this.MyEncoding;
  140. //加入收件者
  141. if (arrayStrToAddressAndName != null)
  142. {
  143. for (int i = 0; i < arrayStrToAddressAndName.Count; i++)
  144. {
  145. MailAccountInfo mai = arrayStrToAddressAndName[i];
  146. if (!string.IsNullOrWhiteSpace(mai.EMail))
  147. {
  148. mm.To.Add(mai.EMail);
  149. }
  150. }
  151. }
  152. //加入CC
  153. if (arrayStrCCAddressAndName != null)
  154. {
  155. for (int i = 0; i < arrayStrCCAddressAndName.Count; i++)
  156. {
  157. MailAccountInfo mai = arrayStrCCAddressAndName[i];
  158. if (!string.IsNullOrWhiteSpace(mai.EMail))
  159. {
  160. mm.CC.Add(mai.EMail);
  161. }
  162. }
  163. }
  164. //加入BCC
  165. if (arrayStrBCCAddressAndName != null)
  166. {
  167. for (int i = 0; i < arrayStrBCCAddressAndName.Count; i++)
  168. {
  169. MailAccountInfo mai = arrayStrBCCAddressAndName[i];
  170. if (!string.IsNullOrWhiteSpace(mai.EMail))
  171. {
  172. mm.Bcc.Add(mai.EMail);
  173. }
  174. }
  175. }
  176. using System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(this.SMTP, this.Port);
  177. if (!string.IsNullOrWhiteSpace(this.Account) && !string.IsNullOrWhiteSpace(this.EnterCode))
  178. {
  179. smtp.Credentials = new NetworkCredential(this.Account, this.EnterCode);
  180. }
  181. smtp.EnableSsl = this.SSL;
  182. if (UseDefaultCredentials != null)
  183. {
  184. switch (UseDefaultCredentials.ToLower(CultureInfo.CurrentCulture))
  185. {
  186. case "true":
  187. smtp.UseDefaultCredentials = true;
  188. break;
  189. case "false":
  190. smtp.UseDefaultCredentials = false;
  191. break;
  192. default:
  193. break;
  194. }
  195. }
  196. mm.Body = strBody;
  197. if (i_lAttachPaths != null && i_lAttachPaths.Any())
  198. {
  199. foreach (string sPath in i_lAttachPaths)
  200. {
  201. if (File.Exists(sPath))
  202. {
  203. Attachment data = new Attachment(sPath, MediaTypeNames.Application.Octet);
  204. // Add time stamp information for the file.
  205. ContentDisposition disposition = data.ContentDisposition;
  206. disposition.CreationDate = System.IO.File.GetCreationTime(sPath);
  207. disposition.ModificationDate = System.IO.File.GetLastWriteTime(sPath);
  208. disposition.ReadDate = System.IO.File.GetLastAccessTime(sPath);
  209. // Add the file attachment to this e-mail message.
  210. mm.Attachments.Add(data);
  211. }
  212. }
  213. }
  214. smtp.Send(mm);
  215. mm.Dispose();
  216. Logger.Debug("MailHelper Send End");
  217. }
  218. catch
  219. {
  220. sMsg = $"{nameof(Send)} unknwon exception. Call from {i_sMemberName} {i_sSourcePath}({i_nCodeLine}).";
  221. }
  222. return sMsg;
  223. }
  224. public static string SendAdminMail(string i_sTitle, string i_sBody,
  225. [System.Runtime.CompilerServices.CallerLineNumber] int i_nCodeLine = 0,
  226. [System.Runtime.CompilerServices.CallerMemberName] string i_sMemberName = "",
  227. [System.Runtime.CompilerServices.CallerFilePath] string i_sSourcePath = ""
  228. )
  229. {
  230. string sMsg;
  231. try
  232. {
  233. do
  234. {
  235. sMsg = SystemSettingHelper.GetSetting(BLWording.SYSTEMSETTING_SYSTEMERRORMAIL, out tb_sys_system_setting sResult);
  236. if (sMsg != null || sResult.key_value == null || sResult.key_value.Trim().Length == 0)
  237. {
  238. break;
  239. }
  240. string[] saMail = sResult.key_value.Split(";,".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
  241. List<MailAccountInfo> lmaReceiver = new List<MailAccountInfo>();
  242. foreach (string sMail in saMail)
  243. {
  244. lmaReceiver.Add(new MailAccountInfo()
  245. {
  246. EMail = sMail,
  247. Name = sMail.Substring(0, sMail.IndexOf("@", StringComparison.OrdinalIgnoreCase))
  248. });
  249. }
  250. MailHelper mh = new MailHelper();
  251. sMsg = mh.Send($"{i_sTitle}", i_sBody, lmaReceiver);
  252. if (sMsg != null)
  253. {
  254. break;
  255. }
  256. }
  257. while (false);
  258. }
  259. catch (Exception ex)
  260. {
  261. LogHelper.DBLog(Util.GetLastExceptionMsg(ex), i_nCodeLine, i_sMemberName, i_sSourcePath);
  262. sMsg = $"{nameof(SendAdminMail)} unknwon exception. Call from {i_sMemberName} {i_sSourcePath}({i_nCodeLine}).";
  263. #if DEBUG
  264. System.Diagnostics.Debug.WriteLine(sMsg);
  265. #endif
  266. }
  267. return sMsg;
  268. }
  269. }
  270. }