123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184 |
- 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<string, SmtpClient> smtpClients { get; } = new ConcurrentDictionary<string, SmtpClient>();
- public MailFactory( ILogger<MailFactory> logger, IConfiguration _configuration)
- {
- _optionsMonitor= new MailOptions();
- _optionsMonitor.fromMail=_configuration.GetValue<string>("MailOption:fromMail");
- _optionsMonitor.port=_configuration.GetValue<Int32>("MailOption:port");
- _optionsMonitor.smtp=_configuration.GetValue<string>("MailOption:smtp");
- _optionsMonitor.username=_configuration.GetValue<string>("MailOption:username");
- _optionsMonitor.password=_configuration.GetValue<string>("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<MailFactory>();
- 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<TMDOrder>(userToken, new Microsoft.Azure.Cosmos.PartitionKey("TMDOrder"));
- order.invoiceNotify=result;
- await azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).ReplaceItemAsync<TMDOrder>(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<TMDOrder>(userToken, new PartitionKey("TMDOrder"));
- // order.invoiceNotify=result;
- // await azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).ReplaceItemAsync<TMDOrder>(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; }
- }
- }
|