MailFactory.cs 8.0 KB

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