MailFactory.cs 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. using Microsoft.Extensions.DependencyInjection;
  2. using Microsoft.Extensions.DependencyInjection.Extensions;
  3. using Microsoft.Extensions.Logging;
  4. using Microsoft.Extensions.Options;
  5. using System;
  6. using System.Collections.Concurrent;
  7. using System.Collections.Generic;
  8. using System.ComponentModel;
  9. using System.Linq;
  10. using System.Net;
  11. using System.Net.Mail;
  12. using System.Text;
  13. using System.Threading.Tasks;
  14. namespace TEAMModelOS.SDK.DI.Mail
  15. {
  16. public class MailFactory
  17. {
  18. private readonly ILogger _logger;
  19. private readonly IOptionsMonitor<MailOptions> _optionsMonitor;
  20. private ConcurrentDictionary<string, SmtpClient> smtpClients { get; } = new ConcurrentDictionary<string, SmtpClient>();
  21. public MailFactory(IOptionsMonitor<MailOptions> optionsMonitor, ILogger<MailFactory> logger)
  22. {
  23. if (optionsMonitor == null) throw new ArgumentNullException(nameof(optionsMonitor));
  24. _optionsMonitor = optionsMonitor;
  25. _logger = logger;
  26. }
  27. public SmtpClient GetSmtpClient(string name = "Default")
  28. {
  29. try
  30. {
  31. var cklient = smtpClients.GetOrAdd(name, x => new SmtpClient(_optionsMonitor.Get(name).smtp)
  32. {
  33. Credentials= new NetworkCredential(_optionsMonitor.Get(name).username, _optionsMonitor.Get(name).password),
  34. UseDefaultCredentials=false,
  35. EnableSsl=true
  36. });
  37. //955 是错误的。
  38. cklient.Port= _optionsMonitor.Get(name).port;
  39. return cklient;
  40. }
  41. catch (OptionsValidationException e)
  42. {
  43. _logger?.LogWarning(e, e.Message);
  44. throw;
  45. }
  46. }
  47. }
  48. public static class NetMailFactoryExtensions
  49. {
  50. public static IServiceCollection AddNetMail(this IServiceCollection services, MailOptions mailOptions, string name = "Default")
  51. {
  52. if (services == null) throw new ArgumentNullException(nameof(services));
  53. if (mailOptions == null) throw new ArgumentNullException(nameof(mailOptions));
  54. services.TryAddSingleton<MailFactory>();
  55. services.Configure<MailOptions>(name, o => {
  56. o.Name = name;
  57. o.fromMail=mailOptions.fromMail;
  58. o.port=mailOptions.port;
  59. o.smtp=mailOptions.smtp;
  60. o.username=mailOptions.username;
  61. o.password=mailOptions.password;
  62. });
  63. return services;
  64. }
  65. public static string SendEmail(this SmtpClient smtpClient, AzureRedisFactory coreRedisFactory, string subject, string content, string toMail,string tmdid,string tmdname ,string sender = "醍摩豆客服助手")
  66. {
  67. if (smtpClient!=null)
  68. {
  69. NetworkCredential networkCredential = (NetworkCredential)smtpClient.Credentials!;
  70. MailMessage mailMessage = new MailMessage(new MailAddress(networkCredential.UserName, sender), new MailAddress(toMail, $"{tmdname}({tmdid})"));
  71. mailMessage.Subject = subject;
  72. mailMessage.Body = content;
  73. mailMessage.IsBodyHtml = true;
  74. smtpClient.SendCompleted+=async (sender, e) =>
  75. {
  76. int result = 0;
  77. string userToken = $"{e.UserState}";
  78. if (e.Cancelled)
  79. {
  80. result=0;
  81. Console.WriteLine("Email sending was canceled.");
  82. }
  83. else if (e.Error != null)
  84. {
  85. result=1;
  86. Console.WriteLine("Error while sending email: " + e.Error.ToString());
  87. }
  88. else
  89. {
  90. result=2;
  91. Console.WriteLine("Email was sent successfully.");
  92. }
  93. await coreRedisFactory.GetRedisClient(8).StringSetAsync($"MailToken:{userToken}", result, expiry: new TimeSpan(0, 2, 0));
  94. };
  95. string token = Guid.NewGuid().ToString("N");
  96. smtpClient.SendAsync(mailMessage, token);
  97. return token;
  98. }
  99. else {
  100. return null;
  101. }
  102. }
  103. // 处理 SendCompleted 事件
  104. private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
  105. {
  106. if (e.Cancelled)
  107. {
  108. Console.WriteLine("Email sending was canceled.");
  109. }
  110. else if (e.Error != null)
  111. {
  112. Console.WriteLine("Error while sending email: " + e.Error.ToString());
  113. }
  114. else
  115. {
  116. Console.WriteLine("Email was sent successfully.");
  117. }
  118. }
  119. }
  120. public class MailOptions
  121. {
  122. public string? Name { get; set; }
  123. public string? fromMail { get; set; }
  124. public string? smtp { get; set; }
  125. public string? username { get; set; }
  126. public string? password { get; set; }
  127. public int port { get; set; }
  128. }
  129. }