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.

717 lines
29 KiB

2 years ago
2 years ago
  1. using EasyBL.WebApi.Message;
  2. using Entity.Sugar;
  3. using HtmlAgilityPack;
  4. using SqlSugar;
  5. using SqlSugar.Base;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Configuration;
  9. using System.Linq;
  10. using System.Net.Mail;
  11. using System.Text;
  12. using System.Text.RegularExpressions;
  13. using System.Web;
  14. using System.Web.Services.Protocols;
  15. namespace EasyBL
  16. {
  17. public class MailService : ServiceBase
  18. {
  19. #region Declare Region
  20. private string _sErrorMessages = string.Empty;
  21. #endregion Declare Region
  22. #region Property Region
  23. /// <summary>
  24. /// 組織ID
  25. /// </summary>
  26. public string OrgID { get; set; } = string.Empty;
  27. /// <summary>
  28. /// 組織ID
  29. /// </summary>
  30. public bool IsConfig { get; set; } = false;
  31. /// <summary>
  32. /// 錯誤信息
  33. /// </summary>
  34. public string ErrorMessages
  35. {
  36. set { _sErrorMessages += value + ";"; }
  37. get { return _sErrorMessages; }
  38. }
  39. #endregion Property Region
  40. public readonly EasyNet.Common.Map mailSetting = new EasyNet.Common.Map();
  41. public MailService(string orgid, bool isconfig = false)
  42. {
  43. OrgID = orgid;
  44. IsConfig = isconfig;
  45. var array = new string[] { @"MailEncoding", "FromName", "FromEmail", "FromUserId", "FromPassword", "Server", "ServerPort", "Timeout", "SSL" };
  46. mailSetting = Common.GetSystemSettings(OrgID, array);
  47. }
  48. #region 郵件寄送
  49. /// <summary>
  50. /// 郵件寄送
  51. /// </summary>
  52. /// <param name="i_crm">todo: describe i_crm parameter on SendMail</param>
  53. /// <returns></returns>
  54. public ResponseMessage SendMail(RequestMessage i_crm)
  55. {
  56. ResponseMessage rm = null;
  57. string sMsg = null;
  58. try
  59. {
  60. do
  61. {
  62. //string sParams = _fetchString(i_crm, "Params");
  63. var bSend = SendMail(i_crm.DATA["Params"], out sMsg);
  64. if (sMsg != null)
  65. {
  66. break;
  67. }
  68. } while (false);
  69. rm = new SuccessResponseMessage(null, i_crm);
  70. }
  71. catch (Exception ex)
  72. {
  73. sMsg = Util.GetLastExceptionMsg(ex);
  74. LogAndSendEmail(sMsg + "Param:" + JsonToString(i_crm), ex, i_crm.ORIGID, i_crm.USERID, nameof(MailService), nameof(MailService), "SendMail(郵件寄送)", "", "", "");
  75. }
  76. finally
  77. {
  78. if (null != sMsg)
  79. {
  80. rm = new ErrorResponseMessage(sMsg, i_crm);
  81. }
  82. }
  83. return rm;
  84. }
  85. #endregion 郵件寄送
  86. public bool SendMail(Object Params, out string o_sError)
  87. {
  88. var bSend = false;
  89. string sError = null;
  90. try
  91. {
  92. do
  93. {
  94. var db = SugarBase.GetIntance();
  95. var mail = new Emails();
  96. var dic = Params as Dictionary<string, object>;
  97. if (!dic.ContainsKey(BLWording.EMAILTO))
  98. {
  99. sError = "缺少必要的參數:‘" + BLWording.EMAILTO + "’"; break;
  100. }
  101. if (!dic.ContainsKey(BLWording.MAILTEMPID) && !dic.ContainsKey(BLWording.EMAILBODY))
  102. {
  103. sError = "缺少必要的參數:‘" + BLWording.MAILTEMPID + "’ 或 ‘" + BLWording.EMAILBODY + "’"; break;
  104. }
  105. if (dic.ContainsKey(BLWording.EMAILBODY) && !dic.ContainsKey(BLWording.TITLE))
  106. {
  107. sError = "如果不是配置郵件模板,‘" + BLWording.TITLE + "’是必要的參數."; break;
  108. }
  109. if (dic.ContainsKey(BLWording.FROMUSERID) && !dic.ContainsKey(BLWording.FROMEMAIL))
  110. {
  111. //抓取當前使用者資料
  112. var sFromUserId = dic[BLWording.FROMUSERID].ToString();
  113. var saUserFrom = db.UnionAll(
  114. db.Queryable<OTB_SYS_Members>().Where(it => it.Effective == "Y").Select(x => new AllUsers
  115. {
  116. OrgID = x.OrgID,
  117. MemberID = x.MemberID,
  118. MemberName = x.MemberName,
  119. Email = x.Email
  120. }),
  121. db.Queryable<OTB_CRM_Customers>().Where(it => it.Effective == "Y").Select(x => new AllUsers
  122. {
  123. OrgID = x.OrgID,
  124. MemberID = x.guid,
  125. MemberName = SqlFunc.IIF(SqlFunc.HasValue(x.CustomerCName), x.CustomerCName, x.CustomerEName),
  126. Email = x.Email
  127. }))
  128. .Where(it => it.MemberID == sFromUserId && it.OrgID == OrgID).ToList()
  129. .ToList();
  130. if (saUserFrom.Count == 0)
  131. {
  132. sError = "發件人信息有誤";
  133. break;
  134. }
  135. var oUserFrom = saUserFrom.First();
  136. mail.FromUserID = oUserFrom.MemberID;
  137. mail.FromUserName = oUserFrom.MemberName;
  138. mail.FromEmail = oUserFrom.Email;
  139. }
  140. if (dic.ContainsKey(BLWording.FROMUSERNAME) && string.IsNullOrWhiteSpace(mail.FromUserName))
  141. {
  142. mail.FromUserName = dic[BLWording.FROMUSERNAME].ToString();
  143. }
  144. if (dic.ContainsKey(BLWording.FROMEMAIL) && string.IsNullOrWhiteSpace(mail.FromEmail))
  145. {
  146. mail.FromEmail = dic[BLWording.FROMEMAIL].ToString();
  147. }
  148. var Tos = new List<EmailTo>();
  149. var listTo = dic[BLWording.EMAILTO] as Object[];
  150. var sToUserName = "";
  151. var builder = new StringBuilder();
  152. builder.Append(sToUserName);
  153. foreach (Object mailto in listTo)
  154. {
  155. var dicto = mailto as Dictionary<string, object>;
  156. var to = new EmailTo();
  157. if (dicto.Keys.Contains("ToEmail"))
  158. {
  159. to.ToUserName = dicto["ToUserName"].ToString();
  160. to.ToEmail = dicto["ToEmail"].ToString();
  161. }
  162. else
  163. {
  164. //抓取當前使用者資料
  165. var sToUserId = dic[BLWording.TOUSERID].ToString();
  166. var saUserTo = db.UnionAll(
  167. db.Queryable<OTB_SYS_Members>().Where(it => it.Effective == "Y").Select(x => new AllUsers
  168. {
  169. OrgID = x.OrgID,
  170. MemberID = x.MemberID,
  171. MemberName = x.MemberName,
  172. Email = x.Email
  173. }),
  174. db.Queryable<OTB_CRM_Customers>().Where(it => it.Effective == "Y").Select(x => new AllUsers
  175. {
  176. OrgID = x.OrgID,
  177. MemberID = x.guid,
  178. MemberName = SqlFunc.IIF(SqlFunc.HasValue(x.CustomerCName), x.CustomerCName, x.CustomerEName),
  179. Email = x.Email
  180. }))
  181. .Where(it => it.MemberID == sToUserId && it.OrgID == OrgID).ToList()
  182. .ToList();
  183. if (saUserTo.Count == 0)
  184. {
  185. break;
  186. }
  187. var oUserTo = saUserTo.First();
  188. to.ToUserID = oUserTo.MemberID;
  189. to.ToUserName = oUserTo.MemberName;
  190. to.ToEmail = oUserTo.Email;
  191. }
  192. to.Type = (dicto["Type"] != null && dicto["Type"].ToString() != "") ? dicto["Type"].ToString() : nameof(to);
  193. builder.Append(to.ToUserName + ",");
  194. Tos.Add(to);
  195. }
  196. sToUserName = builder.ToString();
  197. sToUserName = (sToUserName + ",").Replace(",,", "");
  198. if (Tos.Count == 0) { sError = "收件人信息有誤"; break; }
  199. mail.EmailTo = Tos;
  200. if (dic.ContainsKey(BLWording.EMAILBODY))
  201. {
  202. mail.EmailBody = dic[BLWording.EMAILBODY].ToString();
  203. }
  204. else
  205. {
  206. //獲取Email郵件格式
  207. var sEmailTemplId = dic[BLWording.MAILTEMPID].ToString();
  208. var oEmailTempl = new OTB_SYS_Email();
  209. var saEmailTempl = db.Queryable<OTB_SYS_Email>()
  210. .Where(it => it.EmailID == sEmailTemplId && it.OrgID == OrgID).ToList();
  211. if (saEmailTempl.Count == 0)
  212. {
  213. sError = "找不到對應的模板";
  214. break;
  215. }
  216. oEmailTempl = saEmailTempl.First();
  217. mail.EmailBody = oEmailTempl.BodyHtml;
  218. mail.Title = oEmailTempl.EmailSubject;
  219. }
  220. if (dic.ContainsKey(BLWording.TITLE))
  221. {
  222. mail.Title = dic[BLWording.TITLE].ToString();
  223. }
  224. if (dic.ContainsKey(BLWording.ATTACHMENTS))
  225. {
  226. mail.Attachments = dic[BLWording.ATTACHMENTS] as Object[];
  227. }
  228. var sBaseUrl = HttpContext.Current.Request.Url.ToString().Replace(HttpContext.Current.Request.RawUrl, "");
  229. mail.EmailBody = mail.EmailBody.Replace("{{:Url}}", sBaseUrl).Replace("{{:FromUserName}}", mail.FromUserName);
  230. if (dic.ContainsKey(BLWording.MAILDATA))
  231. {
  232. var dicData = dic[BLWording.MAILDATA] as Dictionary<string, object>;
  233. foreach (var key in dicData.Keys)
  234. {
  235. mail.EmailBody = mail.EmailBody.Replace("{{:" + key + "}}", dicData[key].ToString());
  236. }
  237. mail.EmailBody = mail.EmailBody.Replace("{{:ToUserName}}", sToUserName);
  238. }
  239. //處理需要隱藏的tr標籤
  240. var doc = new HtmlDocument();
  241. doc.LoadHtml(mail.EmailBody);
  242. foreach (HtmlNode NodeTb in doc.DocumentNode.SelectNodes("//tr"))
  243. {
  244. if (NodeTb.Attributes["style"] != null && NodeTb.Attributes["style"].Value.IndexOf("display:none") > -1)
  245. {
  246. NodeTb.Remove();
  247. }
  248. }
  249. mail.EmailBody = doc.DocumentNode.OuterHtml; //總模版
  250. bSend = MailFactory(mail, out sError);
  251. } while (false);
  252. return bSend;
  253. }
  254. catch (Exception ex)
  255. {
  256. sError = ex.Message;
  257. Logger.Error("MailService.SendMail Error:" + sError + " Params:" + JsonToString(Params), ex);
  258. return bSend;
  259. }
  260. finally
  261. {
  262. o_sError = sError;
  263. }
  264. }
  265. public bool MailFactory(Emails i_oEmail, out string o_sError)
  266. {
  267. var bSend = false;
  268. string sError = null;
  269. try
  270. {
  271. do
  272. {
  273. var objEmail = new MailMessage();
  274. //**寄件者信箱**
  275. var sFromName = mailSetting["FromName"] != null ? mailSetting["FromName"].ToString() : Common.GetAppSettings("FromName").Trim(); //顯示發件人的名字代替Mail地址
  276. var sMailFrom = mailSetting["FromEmail"] != null ? mailSetting["FromEmail"].ToString() : Common.GetAppSettings("FromEmail").Trim(); //發件人地址
  277. sMailFrom = i_oEmail.FromEmail ?? sMailFrom; //發件人地址
  278. sFromName = i_oEmail.FromUserName ?? sFromName; //系統郵件[請勿回覆]
  279. var o_MailFrom = new MailAddress(sMailFrom, sFromName, Encoding.Default);
  280. objEmail.From = o_MailFrom;
  281. //**收件者信箱**//
  282. objEmail.To.Clear();
  283. objEmail.CC.Clear();
  284. objEmail.Bcc.Clear();
  285. MailAddress o_MailTo;
  286. foreach (EmailTo _EmailTo in i_oEmail.EmailTo)
  287. {
  288. if (_EmailTo.ToEmail != "")
  289. {
  290. o_MailTo = new MailAddress(_EmailTo.ToEmail, _EmailTo.ToUserName);
  291. switch (_EmailTo.Type)
  292. {
  293. case "to":
  294. objEmail.To.Add(o_MailTo);
  295. break;
  296. case "cc":
  297. objEmail.CC.Add(o_MailTo);
  298. break;
  299. case "bcc":
  300. objEmail.Bcc.Add(o_MailTo);
  301. break;
  302. default:
  303. break;
  304. }
  305. }
  306. }
  307. if (i_oEmail.Attachments != null && i_oEmail.Attachments.Length > 0)
  308. {
  309. foreach (string Attachment in i_oEmail.Attachments)
  310. {
  311. var sPath = Regex.Replace(Attachment, @"//|/", @"\");
  312. var attachment = new Attachment(sPath);//<-這是附件部分~先用附件的物件把路徑指定進去~
  313. objEmail.Attachments.Add(attachment); //<-郵件訊息中加入附件
  314. }
  315. }
  316. //**信件標題**//
  317. objEmail.Subject = i_oEmail.Title;
  318. //**信件主旨**//
  319. objEmail.Body = i_oEmail.EmailBody;
  320. //objEmail.Body = HttpContext.Current.Server.HtmlDecode(objEmail.Body);
  321. objEmail.IsBodyHtml = true;
  322. //'**设置正文的编码形式.这里的设置为取系统默认编码
  323. //objEmail.BodyEncoding = System.Text.Encoding.Default;
  324. objEmail.BodyEncoding = Encoding.UTF8;
  325. //'**设置主题的编码形式.这里的设置为取系统默认编码
  326. //objEmail.SubjectEncoding = System.Text.Encoding.Default;
  327. objEmail.SubjectEncoding = Encoding.UTF8;
  328. objEmail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
  329. //**信件送出**
  330. if (i_oEmail.IsCCSelf && i_oEmail.FromEmail != null && i_oEmail.FromEmail != "")
  331. {
  332. bSend = this.SendMailNET(objEmail);
  333. }
  334. else
  335. {
  336. bSend = this.SendMailNET_NoSelf(objEmail);
  337. }
  338. } while (false);
  339. return bSend;
  340. }
  341. catch (Exception ex)
  342. {
  343. sError = ex.Message;
  344. Logger.Error("MailService.MailFactory Error:" + sError + " Params:" + JsonToString(i_oEmail), ex);
  345. return bSend;
  346. }
  347. finally
  348. {
  349. o_sError = sError;
  350. }
  351. }
  352. #region Definition Public Methods
  353. #region SendMail
  354. /// <summary>
  355. /// 同步發送電子郵件
  356. /// </summary>
  357. /// <param name="o_myMessage">電子郵件</param>
  358. [SoapRpcMethod(OneWay = true)]
  359. public void SendMail(MailMessage o_myMessage)
  360. {
  361. #region "重構在 GetEmailConfig()"
  362. var o_myMailServer = GetEmailConfig(); //new SmtpClient(sServer);//寄件服務器地址,端口
  363. #endregion "重構在 GetEmailConfig()"
  364. try
  365. {
  366. object userState = o_myMailServer;
  367. //o_myMailServer.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
  368. o_myMailServer.SendAsync(o_myMessage, userState);
  369. }
  370. catch (SmtpException ex)
  371. {
  372. ErrorMessages = ex.Message;
  373. Logger.Error(ex);
  374. }
  375. }
  376. /// <summary>
  377. /// 同步發送電子郵件組
  378. /// </summary>
  379. /// <param name="o_myMessage">電子郵件組</param>
  380. [SoapRpcMethod(OneWay = true)]
  381. public void SendMail(MailMessage[] o_myMessage)
  382. {
  383. try
  384. {
  385. for (int i = 0; i <= o_myMessage.Length - 1; i++)
  386. {
  387. //Add by Alina 20131216 170 146 信件通知超連結 Star
  388. o_myMessage[i].Body = o_myMessage[i].Body;
  389. //Add by Alina 20131216 170 146 信件通知超連結 End
  390. SendMail(o_myMessage[i]);//發送
  391. }
  392. }
  393. catch (SmtpException ex)
  394. {
  395. ErrorMessages = ex.Message;
  396. Logger.Error(ex);
  397. }
  398. }
  399. #endregion SendMail
  400. #region SendMailNET
  401. /// <summary>
  402. /// 同步發送電子郵件
  403. /// </summary>
  404. /// <param name="o_myMessage">電子郵件</param>
  405. /// <returns></returns>
  406. public bool SendMailNET_NoSelf(MailMessage o_myMessage)
  407. {
  408. try
  409. {
  410. Logger.Debug("發送郵件開始");
  411. var o_myMailServer = GetEmailConfig(); //new SmtpClient(sServer);//寄件服務器地址,端口
  412. //發送Mail
  413. o_myMailServer.Send(o_myMessage);
  414. Logger.Debug("FormName:" + o_myMessage.From.DisplayName + ";FormMail:" + o_myMessage.From.Address);
  415. Logger.Debug("發送郵件結束");
  416. return true;
  417. }
  418. catch (SmtpException ex)
  419. {
  420. ErrorMessages = ex.Message;
  421. Logger.Error(ex);
  422. return false;
  423. }
  424. }
  425. /// <summary>
  426. /// 同步發送電子郵件
  427. /// </summary>
  428. /// <param name="o_myMessage">電子郵件</param>
  429. /// <returns></returns>
  430. public bool SendMailNET(MailMessage o_myMessage)
  431. {
  432. try
  433. {
  434. Logger.Debug("發送郵件開始");
  435. var o_myMailServer = GetEmailConfig(); //new SmtpClient(sServer);//寄件服務器地址,端口
  436. //Add by Alina 需要把發件者的信息添加到抄送人中
  437. var reg = new Regex(@"(\w*)(\()*");
  438. var strFromName = o_myMessage.From.DisplayName;//人員名稱
  439. var strFromMail = o_myMessage.From.Address;//人員Mail
  440. var m = reg.Match(strFromName);
  441. strFromName = m.Groups[1].Value;
  442. var o_MailTo = new MailAddress(strFromMail, strFromName);
  443. o_myMessage.From = o_MailTo;//發件者的信息
  444. o_myMessage.CC.Add(o_myMessage.From);//把發件者的信息添加到抄送人中
  445. //發送Mail
  446. Logger.Debug("FormName:" + o_myMessage.From.DisplayName + ";FormMail:" + o_myMessage.From.Address);
  447. o_myMailServer.Send(o_myMessage);
  448. return true;
  449. }
  450. catch (SmtpException ex)
  451. {
  452. ErrorMessages = ex.Message;
  453. Logger.Error(ex);
  454. return false;
  455. }
  456. }
  457. /// <summary>
  458. /// 同步發送電子郵件組
  459. /// </summary>
  460. /// <param name="o_myMessage">電子郵件組</param>
  461. /// <returns></returns>
  462. public bool SendMailNET(MailMessage[] o_myMessage)
  463. {
  464. var blOK = true;
  465. try
  466. {
  467. for (int i = 0; i <= o_myMessage.Length - 1; i++)
  468. {
  469. var blThisOK = SendMailNET(o_myMessage[i]);//發送
  470. if (blThisOK == false)
  471. {
  472. //只記錄發送失敗的
  473. blOK = false;
  474. }
  475. }
  476. }
  477. catch (SmtpException ex)
  478. {
  479. ErrorMessages = ex.Message;
  480. Logger.Error(ex);
  481. }
  482. return blOK;
  483. }
  484. #endregion SendMailNET
  485. #endregion Definition Public Methods
  486. #region Definition Private Methods
  487. #region "GetEmailConfig"
  488. /// <summary>
  489. /// 提供本類中其它公有郵件功能,取得基本smtp設定.
  490. /// </summary>
  491. /// <returns></returns>
  492. private SmtpClient GetEmailConfig()
  493. {
  494. var sMailEncoding = IsConfig || mailSetting["MailEncoding"] == null ? ConfigurationManager.AppSettings["MailEncoding"].ToString().Trim() : mailSetting["MailEncoding"].ToString().Trim(); //設置字集防止亂碼
  495. var sFromUserid = IsConfig || mailSetting["FromUserId"] == null ? ConfigurationManager.AppSettings["FromUserId"].ToString().Trim() : mailSetting["FromUserId"].ToString().Trim(); //發件人的帳號
  496. var sFromPassword = IsConfig || mailSetting["FromPassword"] == null ? ConfigurationManager.AppSettings["FromPassword"].Trim() : mailSetting["FromPassword"].ToString(); //發件人的密碼
  497. var sServer = IsConfig || mailSetting["Server"] == null ? ConfigurationManager.AppSettings["Server"].ToString().Trim() : mailSetting["Server"].ToString().Trim(); //發送郵件服務器的IP地址
  498. int i32ServerPort;
  499. int.TryParse(IsConfig || mailSetting["ServerPort"] == null ? ConfigurationManager.AppSettings["ServerPort"].ToString().Trim() : mailSetting["ServerPort"].ToString().Trim(), out i32ServerPort); //發送郵件服務器的端口
  500. int iTimeout;
  501. int.TryParse(IsConfig || mailSetting["Timeout"] == null ? ConfigurationManager.AppSettings["Timeout"].ToString().Trim() : mailSetting["Timeout"].ToString(), out iTimeout); //發送郵件超時時間
  502. var blSSLYES = (IsConfig || mailSetting["SSL"] == null ? ConfigurationManager.AppSettings["SSL"].ToString().Trim() : mailSetting["SSL"].ToString().Trim()).Equals("true") ? true : false;//是否開啟SSL驗證
  503. var o_myMailServer = new SmtpClient(sServer)
  504. {
  505. Host = sServer
  506. };//寄件服務器地址,端口
  507. if (i32ServerPort != 0)
  508. {
  509. o_myMailServer.Port = i32ServerPort;
  510. }
  511. o_myMailServer.EnableSsl = blSSLYES;//是否開啟SSL驗證
  512. //o_myMailServer.DeliveryMethod = SmtpDeliveryMethod.Network;
  513. if (iTimeout != 0)
  514. {
  515. o_myMailServer.Timeout = iTimeout * 1000; //若郵件過大,請手動加長時間, 1000約等於1秒
  516. }
  517. if (!sFromPassword.Equals(""))
  518. {
  519. o_myMailServer.UseDefaultCredentials = false;
  520. o_myMailServer.Credentials = new System.Net.NetworkCredential(sFromUserid, sFromPassword);//登錄會員名和密碼
  521. }
  522. return o_myMailServer;
  523. }
  524. #endregion "GetEmailConfig"
  525. #endregion Definition Private Methods
  526. #region Page Control Event
  527. //#region SendMail
  528. //private void test()
  529. //{
  530. // System.Net.Mail.MailMessage objEmail = new System.Net.Mail.MailMessage();
  531. // //**寄件者信箱** string strMailFrom = ""; string FromName = ""; if (strMailFrom.Equals("") ==
  532. // false) { System.Net.Mail.MailAddress o_MailFrom = new
  533. // System.Net.Mail.MailAddress(strMailFrom, FromName, Encoding.Default); objEmail.From =
  534. // o_MailFrom; }
  535. // //**收件者信箱** string strMailTo = ""; if (strMailTo.Equals("") == false) {
  536. // System.Net.Mail.MailAddress o_MailTo = new System.Net.Mail.MailAddress(strMailTo);
  537. // objEmail.To.Add(o_MailTo); }
  538. // //**副本收件者信箱** string strMailCC = ""; if (strMailCC.Equals("") == false) { //隱藏副本收件者信箱不為空
  539. // objEmail.CC.Add(strMailCC); }
  540. // //**隱藏副本收件者信箱** string strMailbcc = ""; if (strMailbcc.Equals("") == false) {
  541. // //隱藏副本收件者信箱不為空 objEmail.Bcc.Add(strMailbcc); }
  542. // //**信件主旨** objEmail.Subject = "信件主旨";
  543. // //**信件主體(HTML模式)** //objEmail.HTMLbody = ""
  544. // //**信件主體(文字模式)** objEmail.Body = "信件主體";
  545. // //'**设置正文的编码形式.这里的设置为取系统默认编码 objEmail.BodyEncoding = System.Text.Encoding.Default;
  546. // //'**设置主题的编码形式.这里的设置为取系统默认编码 objEmail.SubjectEncoding = System.Text.Encoding.Default;
  547. // //'**描述Mail傳遞告知選項 // Delay:通知传送是否延迟。 // Never:从不通知。 // None:没有通知。 // OnFailure:通知传送是否失败。
  548. // // OnSuccess:通知传送是否成功。 objEmail.DeliveryNotificationOptions = System.Net.Mail.DeliveryNotificationOptions.OnFailure;
  549. // //**信件送出** SendMailNET(objEmail); SendMailAsync(objEmail);
  550. //}
  551. //#endregion
  552. #endregion Page Control Event
  553. }
  554. public class Emails
  555. {
  556. public string FromOrgID { get; set; }
  557. public string FromUserID { get; set; }
  558. public string FromUserName { get; set; }
  559. public string FromEmail { get; set; }
  560. public string Title { get; set; }
  561. public string EmailBody { get; set; }
  562. public bool IsCCSelf { get; set; }
  563. public List<EmailTo> EmailTo { get; set; }
  564. public object[] Attachments { get; set; }
  565. }
  566. public class EmailTo
  567. {
  568. public string ToUserID { get; set; }
  569. public string ToUserName { get; set; }
  570. public string ToEmail { get; set; }
  571. public string Type { get; set; }
  572. }
  573. public class AllUsers
  574. {
  575. public string OrgID { get; set; }
  576. public string MemberID { get; set; }
  577. public string MemberName { get; set; }
  578. public string Email { get; set; }
  579. }
  580. public class OutlookDotComMail
  581. {
  582. //string mailUser = "dd24166@outlook.com";
  583. //string mailUserPwd = "654321zzz";
  584. //var sender = new OutlookDotComMail(mailUser, mailUserPwd);
  585. //sender.SendMail("john.yuan@origtek.com.cn", "Test Mail", "Hello!");
  586. //string mailUser = "info@eurotran.com";
  587. //string mailUserPwd = "@in27856000!";
  588. //var sender = new OutlookDotComMail(mailUser, mailUserPwd);
  589. //sender.SendMail("john.yuan@origtek.com.cn", "Test Mail!", "Hello!!!!");
  590. private string _sender = "";
  591. private string _password = "";
  592. public OutlookDotComMail(string sender, string password)
  593. {
  594. _sender = sender;
  595. _password = password;
  596. }
  597. public void SendMail(string recipient, string subject, string message)
  598. {
  599. //SmtpClient client = new SmtpClient("smtp-mail.outlook.com");
  600. using (var client = new SmtpClient("smtp.office365.com")
  601. {
  602. Port = 587,
  603. DeliveryMethod = SmtpDeliveryMethod.Network,
  604. UseDefaultCredentials = false
  605. })
  606. {
  607. var credentials = new System.Net.NetworkCredential(_sender, _password);
  608. client.EnableSsl = true;
  609. client.Credentials = credentials;
  610. try
  611. {
  612. var mail = new MailMessage(_sender.Trim(), recipient.Trim())
  613. {
  614. Subject = subject,
  615. Body = message
  616. };
  617. client.Send(mail);
  618. }
  619. catch (Exception ex)
  620. {
  621. Console.WriteLine(ex.Message);
  622. throw;
  623. }
  624. }
  625. }
  626. }
  627. }