MailFactory.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. using DocumentFormat.OpenXml.Wordprocessing;
  2. using Microsoft.Extensions.Configuration;
  3. using Microsoft.Extensions.DependencyInjection;
  4. using Microsoft.Extensions.DependencyInjection.Extensions;
  5. using Microsoft.Extensions.Logging;
  6. using Microsoft.Extensions.Options;
  7. using System;
  8. using System.Collections.Concurrent;
  9. using System.Collections.Generic;
  10. using System.ComponentModel;
  11. using System.Linq;
  12. using System.Net;
  13. using System.Net.Mail;
  14. using System.Text;
  15. using System.Threading.Tasks;
  16. using TEAMModelOS.SDK.Models;
  17. namespace TEAMModelOS.SDK.DI.Mail
  18. {
  19. public class MailFactory
  20. {
  21. private readonly ILogger _logger;
  22. private readonly MailOptions _optionsMonitor;
  23. private ConcurrentDictionary<string, SmtpClient> smtpClients { get; } = new ConcurrentDictionary<string, SmtpClient>();
  24. public MailFactory( ILogger<MailFactory> logger, IConfiguration _configuration)
  25. {
  26. _optionsMonitor= new MailOptions();
  27. _optionsMonitor.fromMail=_configuration.GetValue<string>("MailOption:fromMail");
  28. _optionsMonitor.port=_configuration.GetValue<Int32>("MailOption:port");
  29. _optionsMonitor.smtp=_configuration.GetValue<string>("MailOption:smtp");
  30. _optionsMonitor.username=_configuration.GetValue<string>("MailOption:username");
  31. _optionsMonitor.password=_configuration.GetValue<string>("MailOption:password");
  32. _logger = logger;
  33. }
  34. public SmtpClient GetSmtpClient(string name = "Default")
  35. {
  36. try
  37. {
  38. var cklient = smtpClients.GetOrAdd(name, x => new SmtpClient(_optionsMonitor.smtp)
  39. {
  40. Credentials= new NetworkCredential(_optionsMonitor.username, _optionsMonitor.password),
  41. UseDefaultCredentials=false,
  42. EnableSsl=true
  43. });
  44. //955 是错误的。
  45. cklient.Port= _optionsMonitor.port;
  46. return cklient;
  47. }
  48. catch (OptionsValidationException e)
  49. {
  50. _logger?.LogWarning(e, e.Message);
  51. throw;
  52. }
  53. }
  54. }
  55. public static class NetMailFactoryExtensions
  56. {
  57. public static IServiceCollection AddNetMail(this IServiceCollection services )
  58. {
  59. if (services == null) throw new ArgumentNullException(nameof(services));
  60. services.TryAddSingleton<MailFactory>();
  61. return services;
  62. }
  63. public static string SendEmail(this SmtpClient smtpClient, AzureCosmosFactory azureCosmos,DingDing dingDing , TMDOrder order, string subject, string content, string toMail,string tmdid,string tmdname ,string sender = "醍摩豆客服助手")
  64. {
  65. if (smtpClient!=null)
  66. {
  67. NetworkCredential networkCredential = (NetworkCredential)smtpClient.Credentials!;
  68. MailMessage mailMessage = new MailMessage(new MailAddress(networkCredential.UserName, sender), new MailAddress(toMail, $"{tmdname}({tmdid})"));
  69. mailMessage.Subject = subject;
  70. mailMessage.Body = content;
  71. mailMessage.IsBodyHtml = true;
  72. smtpClient.SendCompleted+=async (sender, e) =>
  73. {
  74. int result = -1;
  75. string userToken = $"{e.UserState}";
  76. if (e.Cancelled)
  77. {
  78. result=0;
  79. //Console.WriteLine("Email sending was canceled.");
  80. }
  81. else if (e.Error != null)
  82. {
  83. result=2;
  84. //Console.WriteLine("Error while sending email: " + e.Error.ToString());
  85. }
  86. else
  87. {
  88. result=3;
  89. //Console.WriteLine("Email was sent successfully.");
  90. }
  91. try
  92. {
  93. TMDOrder order = await azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).ReadItemAsync<TMDOrder>(userToken, new Azure.Cosmos.PartitionKey("TMDOrder"));
  94. order.invoiceNotify=result;
  95. await azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).ReplaceItemAsync<TMDOrder>(order, userToken, new Azure.Cosmos.PartitionKey("TMDOrder"));
  96. }
  97. catch(Exception ex)
  98. {
  99. await dingDing.SendBotMsg($"邮箱发送异常,订单ID:{userToken}\n{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  100. }
  101. };
  102. string token =$"{order.order_no}";
  103. smtpClient.SendAsync(mailMessage, token);
  104. return token;
  105. }
  106. else {
  107. return null;
  108. }
  109. }
  110. public static string SendEmail(this SmtpClient smtpClient, AzureCosmosFactory azureCosmos, DingDing dingDing, string eventId, string subject, string content, string toMail, string tmdid, string tmdname, string sender = "醍摩豆客服助手")
  111. {
  112. if (smtpClient!=null)
  113. {
  114. NetworkCredential networkCredential = (NetworkCredential)smtpClient.Credentials!;
  115. MailMessage mailMessage = new MailMessage(new MailAddress(networkCredential.UserName, sender), new MailAddress(toMail, $"{tmdname}({tmdid})"));
  116. mailMessage.Subject = subject;
  117. mailMessage.Body = content;
  118. mailMessage.IsBodyHtml = true;
  119. smtpClient.SendCompleted+=async (sender, e) =>
  120. {
  121. int result = -1;
  122. string userToken = $"{e.UserState}";
  123. if (e.Cancelled)
  124. {
  125. result=0;
  126. //Console.WriteLine("Email sending was canceled.");
  127. }
  128. else if (e.Error != null)
  129. {
  130. result=2;
  131. //Console.WriteLine("Error while sending email: " + e.Error.ToString());
  132. }
  133. else
  134. {
  135. result=3;
  136. //Console.WriteLine("Email was sent successfully.");
  137. }
  138. //try
  139. //{
  140. // TMDOrder order = await azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).ReadItemAsync<TMDOrder>(userToken, new Azure.Cosmos.PartitionKey("TMDOrder"));
  141. // order.invoiceNotify=result;
  142. // await azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).ReplaceItemAsync<TMDOrder>(order, userToken, new Azure.Cosmos.PartitionKey("TMDOrder"));
  143. //}
  144. //catch (Exception ex)
  145. //{
  146. // await dingDing.SendBotMsg($"邮箱发送异常,订单ID:{userToken}\n{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  147. //}
  148. };
  149. string token = eventId;
  150. smtpClient.SendAsync(mailMessage, token);
  151. return token;
  152. }
  153. else
  154. {
  155. return null;
  156. }
  157. }
  158. // 处理 SendCompleted 事件
  159. private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
  160. {
  161. if (e.Cancelled)
  162. {
  163. Console.WriteLine("Email sending was canceled.");
  164. }
  165. else if (e.Error != null)
  166. {
  167. Console.WriteLine("Error while sending email: " + e.Error.ToString());
  168. }
  169. else
  170. {
  171. Console.WriteLine("Email was sent successfully.");
  172. }
  173. }
  174. }
  175. public class MailOptions
  176. {
  177. public string? Name { get; set; }
  178. public string? fromMail { get; set; }
  179. public string? smtp { get; set; }
  180. public string? username { get; set; }
  181. public string? password { get; set; }
  182. public int port { get; set; }
  183. }
  184. }