using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using System; using System.Collections.Concurrent; using System.ComponentModel; using System.Net; using System.Net.Mail; using TEAMModelOS.SDK.Models; namespace TEAMModelOS.SDK.DI.Mail { public class MailFactory { private readonly ILogger _logger; private readonly MailOptions _optionsMonitor; private ConcurrentDictionary smtpClients { get; } = new ConcurrentDictionary(); public MailFactory( ILogger logger, IConfiguration _configuration) { _optionsMonitor= new MailOptions(); _optionsMonitor.fromMail=_configuration.GetValue("MailOption:fromMail"); _optionsMonitor.port=_configuration.GetValue("MailOption:port"); _optionsMonitor.smtp=_configuration.GetValue("MailOption:smtp"); _optionsMonitor.username=_configuration.GetValue("MailOption:username"); _optionsMonitor.password=_configuration.GetValue("MailOption:password"); _logger = logger; } public SmtpClient GetSmtpClient(string name = "Default") { try { var cklient = smtpClients.GetOrAdd(name, x => new SmtpClient(_optionsMonitor.smtp) { Credentials= new NetworkCredential(_optionsMonitor.username, _optionsMonitor.password), UseDefaultCredentials=false, EnableSsl=true }); //955 是错误的。 cklient.Port= _optionsMonitor.port; return cklient; } catch (OptionsValidationException e) { _logger?.LogWarning(e, e.Message); throw; } } } public static class NetMailFactoryExtensions { public static IServiceCollection AddNetMail(this IServiceCollection services ) { if (services == null) throw new ArgumentNullException(nameof(services)); services.TryAddSingleton(); return services; } 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 = "醍摩豆客服助手") { if (smtpClient!=null) { NetworkCredential networkCredential = (NetworkCredential)smtpClient.Credentials!; MailMessage mailMessage = new MailMessage(new MailAddress(networkCredential.UserName, sender), new MailAddress(toMail, $"{tmdname}({tmdid})")); mailMessage.Subject = subject; mailMessage.Body = content; mailMessage.IsBodyHtml = true; smtpClient.SendCompleted+=async (sender, e) => { int result = -1; string userToken = $"{e.UserState}"; if (e.Cancelled) { result=0; //Console.WriteLine("Email sending was canceled."); } else if (e.Error != null) { result=2; //Console.WriteLine("Error while sending email: " + e.Error.ToString()); } else { result=3; //Console.WriteLine("Email was sent successfully."); } try { TMDOrder order = await azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).ReadItemAsync(userToken, new Microsoft.Azure.Cosmos.PartitionKey("TMDOrder")); order.invoiceNotify=result; await azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).ReplaceItemAsync(order, userToken, new Microsoft.Azure.Cosmos.PartitionKey("TMDOrder")); } catch(Exception ex) { await dingDing.SendBotMsg($"邮箱发送异常,订单ID:{userToken}\n{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組); } }; string token =$"{order.order_no}"; smtpClient.SendAsync(mailMessage, token); return token; } else { return null; } } 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 = "醍摩豆客服助手") { if (smtpClient!=null) { NetworkCredential networkCredential = (NetworkCredential)smtpClient.Credentials!; MailMessage mailMessage = new MailMessage(new MailAddress(networkCredential.UserName, sender), new MailAddress(toMail, $"{tmdname}({tmdid})")); mailMessage.Subject = subject; mailMessage.Body = content; mailMessage.IsBodyHtml = true; smtpClient.SendCompleted+=async (sender, e) => { int result = -1; string userToken = $"{e.UserState}"; if (e.Cancelled) { result=0; //Console.WriteLine("Email sending was canceled."); } else if (e.Error != null) { result=2; //Console.WriteLine("Error while sending email: " + e.Error.ToString()); } else { result=3; //Console.WriteLine("Email was sent successfully."); } //try //{ // TMDOrder order = await azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).ReadItemAsync(userToken, new PartitionKey("TMDOrder")); // order.invoiceNotify=result; // await azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).ReplaceItemAsync(order, userToken, new PartitionKey("TMDOrder")); //} //catch (Exception ex) //{ // await dingDing.SendBotMsg($"邮箱发送异常,订单ID:{userToken}\n{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組); //} }; string token = eventId; smtpClient.SendAsync(mailMessage, token); return token; } else { return null; } } // 处理 SendCompleted 事件 private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e) { if (e.Cancelled) { Console.WriteLine("Email sending was canceled."); } else if (e.Error != null) { Console.WriteLine("Error while sending email: " + e.Error.ToString()); } else { Console.WriteLine("Email was sent successfully."); } } } public class MailOptions { public string? Name { get; set; } public string? fromMail { get; set; } public string? smtp { get; set; } public string? username { get; set; } public string? password { get; set; } public int port { get; set; } } }