using CounsellorBL.BLStructure; using log4net; using MonumentDefine; using OT.COM.ArsenalDB; using OT.COM.LogisticsUtil; using SoldierData.EnterprizeV4; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Mail; using System.Net.Mime; using System.Text; namespace CounsellorBL.Helper { /// /// 類別名稱:Mailer /// 類別說明: /// 起始作者: /// 起始日期: /// 最新修改人: /// 最新修改日: /// public partial class MailHelper { /// /// 類別成員、類別屬性說明:_inst /// private ILog _inst = null; protected ILog Logger { get { if (_inst == null) { _inst = LogManager.GetLogger(this.GetType()); } return _inst; } } /// /// 類別成員、類別屬性說明:SMTP /// public string SMTP { get; set; } /// /// 類別成員、類別屬性說明:FromAddress /// public string FromAddress { get; set; } /// /// 類別成員、類別屬性說明:Account /// public string Account { get; set; } /// /// 類別成員、類別屬性說明:EnterCode /// public string EnterCode { get; set; } /// /// 類別成員、類別屬性說明:Name /// public string Name { get; set; } /// /// 類別成員、類別屬性說明:Port /// public int Port { get; set; } /// /// 類別成員、類別屬性說明:ErrorMessage /// public string ErrorMessage { get; set; } /// /// 類別成員、類別屬性說明:SSL /// public bool SSL { get; set; } public string UseDefaultCredentials { get; set; } /// /// 類別成員、類別屬性說明:MyEncoding /// public Encoding MyEncoding { get; set; } /// /// 類別成員、類別屬性說明:建構子 /// public MailHelper() { MyEncoding = Encoding.GetEncoding("UTF-8"); ConcurrentDictionary dicSetting = CustomizeDBMgr.SettingData; string sUseSSL = dicSetting.ContainsKey("USESSL") ? dicSetting["USESSL"] : null; SMTP = dicSetting.ContainsKey("SMTPURL") ? dicSetting["SMTPURL"] : null; FromAddress = dicSetting.ContainsKey("MAILOWNERADDRESS") ? dicSetting["MAILOWNERADDRESS"] : null; Account = dicSetting.ContainsKey("MAILACCOUNT") ? dicSetting["MAILACCOUNT"] : null; EnterCode = dicSetting.ContainsKey("MAILPASS") ? dicSetting["MAILPASS"] : null; Name = dicSetting.ContainsKey("MAILACCOUNT") ? dicSetting["MAILACCOUNT"] : null; Port = dicSetting.ContainsKey("MAILPORT") ? Convert.ToInt32(dicSetting["MAILPORT"], CultureInfo.CurrentCulture) : 587; SSL = (sUseSSL?.ToLower(CultureInfo.CurrentCulture).StartsWith("y", StringComparison.OrdinalIgnoreCase)).Value; MyEncoding = Encoding.GetEncoding("UTF-8"); UseDefaultCredentials = dicSetting.ContainsKey("USEDEFAULTCREDENTIALS") ? dicSetting["USEDEFAULTCREDENTIALS"] : null; } /// /// 函式名稱:Send /// 函式說明:寄信動作 /// 起始作者: /// 起始日期: /// 最新修改人: /// 最新修改日: /// /// 主旨 /// 信件內容 /// 收件者 /// /// 附件 /// CC /// BCC /// public string Send(string i_strSubject, string strBody, List arrayStrToAddressAndName, bool bHTML = true, List arrayStrCCAddressAndName = null, List arrayStrBCCAddressAndName = null, List i_lAttachPaths = null, [System.Runtime.CompilerServices.CallerLineNumber] int i_nCodeLine = 0, [System.Runtime.CompilerServices.CallerMemberName] string i_sMemberName = "", [System.Runtime.CompilerServices.CallerFilePath] string i_sSourcePath = "" ) { string sMsg = null; string strSubject = i_strSubject; Logger.Debug(string.Format(CultureInfo.CurrentCulture, "MailHelper Send Start, Title{0}", strSubject)); try { System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage(); if (!string.IsNullOrWhiteSpace(this.FromAddress)) { mm.Sender = new System.Net.Mail.MailAddress(string.Format(CultureInfo.CurrentCulture, "{1}<{0}>", this.FromAddress, this.Name)); mm.From = new System.Net.Mail.MailAddress(string.Format(CultureInfo.CurrentCulture, "{1}<{0}>", this.FromAddress, this.Name)); } mm.Subject = strSubject; mm.IsBodyHtml = bHTML; mm.Body = strBody; mm.BodyEncoding = this.MyEncoding; //加入收件者 if (arrayStrToAddressAndName != null) { for (int i = 0; i < arrayStrToAddressAndName.Count; i++) { MailAccountInfo mai = arrayStrToAddressAndName[i]; if (!string.IsNullOrWhiteSpace(mai.EMail)) { mm.To.Add(mai.EMail); } } } //加入CC if (arrayStrCCAddressAndName != null) { for (int i = 0; i < arrayStrCCAddressAndName.Count; i++) { MailAccountInfo mai = arrayStrCCAddressAndName[i]; if (!string.IsNullOrWhiteSpace(mai.EMail)) { mm.CC.Add(mai.EMail); } } } //加入BCC if (arrayStrBCCAddressAndName != null) { for (int i = 0; i < arrayStrBCCAddressAndName.Count; i++) { MailAccountInfo mai = arrayStrBCCAddressAndName[i]; if (!string.IsNullOrWhiteSpace(mai.EMail)) { mm.Bcc.Add(mai.EMail); } } } using System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(this.SMTP, this.Port); if (!string.IsNullOrWhiteSpace(this.Account) && !string.IsNullOrWhiteSpace(this.EnterCode)) { smtp.Credentials = new NetworkCredential(this.Account, this.EnterCode); } smtp.EnableSsl = this.SSL; if (UseDefaultCredentials != null) { switch (UseDefaultCredentials.ToLower(CultureInfo.CurrentCulture)) { case "true": smtp.UseDefaultCredentials = true; break; case "false": smtp.UseDefaultCredentials = false; break; default: break; } } mm.Body = strBody; if (i_lAttachPaths != null && i_lAttachPaths.Any()) { foreach (string sPath in i_lAttachPaths) { if (File.Exists(sPath)) { Attachment data = new Attachment(sPath, MediaTypeNames.Application.Octet); // Add time stamp information for the file. ContentDisposition disposition = data.ContentDisposition; disposition.CreationDate = System.IO.File.GetCreationTime(sPath); disposition.ModificationDate = System.IO.File.GetLastWriteTime(sPath); disposition.ReadDate = System.IO.File.GetLastAccessTime(sPath); // Add the file attachment to this e-mail message. mm.Attachments.Add(data); } } } smtp.Send(mm); mm.Dispose(); Logger.Debug("MailHelper Send End"); } catch { sMsg = $"{nameof(Send)} unknwon exception. Call from {i_sMemberName} {i_sSourcePath}({i_nCodeLine})."; } return sMsg; } public static string SendAdminMail(string i_sTitle, string i_sBody, [System.Runtime.CompilerServices.CallerLineNumber] int i_nCodeLine = 0, [System.Runtime.CompilerServices.CallerMemberName] string i_sMemberName = "", [System.Runtime.CompilerServices.CallerFilePath] string i_sSourcePath = "" ) { string sMsg; try { do { sMsg = SystemSettingHelper.GetSetting(BLWording.SYSTEMSETTING_SYSTEMERRORMAIL, out tb_sys_system_setting sResult); if (sMsg != null || sResult.key_value == null || sResult.key_value.Trim().Length == 0) { break; } string[] saMail = sResult.key_value.Split(";,".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); List lmaReceiver = new List(); foreach (string sMail in saMail) { lmaReceiver.Add(new MailAccountInfo() { EMail = sMail, Name = sMail.Substring(0, sMail.IndexOf("@", StringComparison.OrdinalIgnoreCase)) }); } MailHelper mh = new MailHelper(); sMsg = mh.Send($"{i_sTitle}", i_sBody, lmaReceiver); if (sMsg != null) { break; } } while (false); } catch (Exception ex) { LogHelper.DBLog(Util.GetLastExceptionMsg(ex), i_nCodeLine, i_sMemberName, i_sSourcePath); sMsg = $"{nameof(SendAdminMail)} unknwon exception. Call from {i_sMemberName} {i_sSourcePath}({i_nCodeLine})."; #if DEBUG System.Diagnostics.Debug.WriteLine(sMsg); #endif } return sMsg; } } }