EmailService.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. using System.Collections.Concurrent;
  2. using MailKit.Net.Smtp;
  3. using MailKit.Security;
  4. using MimeKit;
  5. using Microsoft.Extensions.Configuration;
  6. namespace Esim.SendMail.Services;
  7. /// <summary>
  8. /// High-performance email service optimized for millions of messages
  9. /// Uses MailKit with connection pooling and batch processing
  10. /// </summary>
  11. public interface IEmailService
  12. {
  13. Task<bool> SendEmailAsync(string to, string subject, string body, bool isHtml = true);
  14. Task<int> SendBatchAsync(IEnumerable<EmailMessage> messages);
  15. void Dispose();
  16. }
  17. public class EmailMessage
  18. {
  19. public int Id { get; set; }
  20. public string To { get; set; } = null!;
  21. public string Subject { get; set; } = null!;
  22. public string Body { get; set; } = null!;
  23. public bool IsHtml { get; set; } = true;
  24. }
  25. public class EmailResult
  26. {
  27. public int MessageId { get; set; }
  28. public bool Success { get; set; }
  29. public string? ErrorMessage { get; set; }
  30. }
  31. public class HighPerformanceEmailService : IEmailService, IDisposable
  32. {
  33. private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(HighPerformanceEmailService));
  34. private readonly IConfiguration _configuration;
  35. private readonly string _smtpServer;
  36. private readonly int _smtpPort;
  37. private readonly string _senderEmail;
  38. private readonly string _senderName;
  39. private readonly string _senderPassword;
  40. private readonly bool _enableSsl;
  41. private readonly int _connectionPoolSize;
  42. private readonly int _maxConcurrentSends;
  43. private readonly int _retryDelayMs;
  44. // Connection pool for SMTP clients
  45. private readonly ConcurrentBag<SmtpClient> _connectionPool;
  46. private readonly SemaphoreSlim _poolSemaphore;
  47. private bool _disposed = false;
  48. public HighPerformanceEmailService(IConfiguration configuration)
  49. {
  50. _configuration = configuration;
  51. _smtpServer = _configuration["Email:SmtpServer"] ?? "smtp.gmail.com";
  52. _smtpPort = int.Parse(_configuration["Email:SmtpPort"] ?? "587");
  53. _senderEmail = _configuration["Email:SenderEmail"] ?? "";
  54. _senderName = _configuration["Email:SenderName"] ?? "EsimLao";
  55. _senderPassword = _configuration["Email:SenderPassword"] ?? "";
  56. _enableSsl = bool.Parse(_configuration["Email:EnableSsl"] ?? "true");
  57. _connectionPoolSize = int.Parse(_configuration["Email:ConnectionPoolSize"] ?? "5");
  58. _maxConcurrentSends = int.Parse(_configuration["Email:MaxConcurrentSends"] ?? "10");
  59. _retryDelayMs = int.Parse(_configuration["Email:RetryDelayMs"] ?? "1000");
  60. _connectionPool = new ConcurrentBag<SmtpClient>();
  61. _poolSemaphore = new SemaphoreSlim(_connectionPoolSize, _connectionPoolSize);
  62. // Pre-initialize connection pool
  63. InitializeConnectionPool();
  64. }
  65. private void InitializeConnectionPool()
  66. {
  67. log.Info($"Initializing SMTP connection pool with {_connectionPoolSize} connections");
  68. for (int i = 0; i < _connectionPoolSize; i++)
  69. {
  70. try
  71. {
  72. var client = CreateConnectedClient();
  73. if (client != null)
  74. {
  75. _connectionPool.Add(client);
  76. }
  77. }
  78. catch (Exception ex)
  79. {
  80. log.Warn($"Failed to create initial SMTP connection {i + 1}: {ex.Message}");
  81. }
  82. }
  83. log.Info($"Connection pool initialized with {_connectionPool.Count} connections");
  84. }
  85. private SmtpClient? CreateConnectedClient()
  86. {
  87. try
  88. {
  89. var client = new SmtpClient();
  90. // Connect with timeout
  91. client.Timeout = 30000; // 30 seconds
  92. client.Connect(_smtpServer, _smtpPort, _enableSsl ? SecureSocketOptions.StartTls : SecureSocketOptions.None);
  93. client.Authenticate(_senderEmail, _senderPassword);
  94. return client;
  95. }
  96. catch (Exception ex)
  97. {
  98. log.Error($"Failed to create SMTP connection: {ex.Message}");
  99. return null;
  100. }
  101. }
  102. private async Task<SmtpClient?> GetClientFromPoolAsync()
  103. {
  104. await _poolSemaphore.WaitAsync();
  105. if (_connectionPool.TryTake(out var client))
  106. {
  107. // Check if connection is still alive
  108. if (client.IsConnected)
  109. {
  110. return client;
  111. }
  112. // Connection dead, try to reconnect
  113. try
  114. {
  115. client.Dispose();
  116. }
  117. catch { }
  118. }
  119. // Create new connection
  120. return CreateConnectedClient();
  121. }
  122. private void ReturnClientToPool(SmtpClient? client)
  123. {
  124. if (client != null && client.IsConnected)
  125. {
  126. _connectionPool.Add(client);
  127. }
  128. else
  129. {
  130. // Try to create a new connection
  131. try
  132. {
  133. var newClient = CreateConnectedClient();
  134. if (newClient != null)
  135. {
  136. _connectionPool.Add(newClient);
  137. }
  138. }
  139. catch { }
  140. }
  141. _poolSemaphore.Release();
  142. }
  143. public async Task<bool> SendEmailAsync(string to, string subject, string body, bool isHtml = true)
  144. {
  145. SmtpClient? client = null;
  146. try
  147. {
  148. client = await GetClientFromPoolAsync();
  149. if (client == null)
  150. {
  151. log.Error("Failed to get SMTP client from pool");
  152. return false;
  153. }
  154. var message = CreateMimeMessage(to, subject, body, isHtml);
  155. await client.SendAsync(message);
  156. log.Debug($"Email sent to {to}");
  157. return true;
  158. }
  159. catch (Exception ex)
  160. {
  161. log.Error($"Failed to send email to {to}: {ex.Message}");
  162. // Force reconnect on error
  163. if (client != null)
  164. {
  165. try { client.Disconnect(true); } catch { }
  166. try { client.Dispose(); } catch { }
  167. client = null;
  168. }
  169. return false;
  170. }
  171. finally
  172. {
  173. ReturnClientToPool(client);
  174. }
  175. }
  176. /// <summary>
  177. /// Send batch of emails with parallel processing
  178. /// Returns number of successfully sent emails
  179. /// </summary>
  180. public async Task<int> SendBatchAsync(IEnumerable<EmailMessage> messages)
  181. {
  182. var messageList = messages.ToList();
  183. if (!messageList.Any()) return 0;
  184. log.Info($"Sending batch of {messageList.Count} emails");
  185. int successCount = 0;
  186. var semaphore = new SemaphoreSlim(_maxConcurrentSends);
  187. var tasks = new List<Task<bool>>();
  188. foreach (var msg in messageList)
  189. {
  190. await semaphore.WaitAsync();
  191. var task = Task.Run(async () =>
  192. {
  193. try
  194. {
  195. return await SendEmailAsync(msg.To, msg.Subject, msg.Body, msg.IsHtml);
  196. }
  197. finally
  198. {
  199. semaphore.Release();
  200. }
  201. });
  202. tasks.Add(task);
  203. }
  204. var results = await Task.WhenAll(tasks);
  205. successCount = results.Count(r => r);
  206. log.Info($"Batch complete: {successCount}/{messageList.Count} successful");
  207. return successCount;
  208. }
  209. private MimeMessage CreateMimeMessage(string to, string subject, string body, bool isHtml)
  210. {
  211. var message = new MimeMessage();
  212. message.From.Add(new MailboxAddress(_senderName, _senderEmail));
  213. message.To.Add(MailboxAddress.Parse(to));
  214. message.Subject = subject;
  215. var bodyBuilder = new BodyBuilder();
  216. if (isHtml)
  217. {
  218. bodyBuilder.HtmlBody = body;
  219. }
  220. else
  221. {
  222. bodyBuilder.TextBody = body;
  223. }
  224. message.Body = bodyBuilder.ToMessageBody();
  225. return message;
  226. }
  227. public void Dispose()
  228. {
  229. if (_disposed) return;
  230. _disposed = true;
  231. log.Info("Disposing email service...");
  232. while (_connectionPool.TryTake(out var client))
  233. {
  234. try
  235. {
  236. if (client.IsConnected)
  237. {
  238. client.Disconnect(true);
  239. }
  240. client.Dispose();
  241. }
  242. catch { }
  243. }
  244. _poolSemaphore.Dispose();
  245. log.Info("Email service disposed");
  246. }
  247. }