From a8e73069c2021ad3150edc2557ac694892e19aa2 Mon Sep 17 00:00:00 2001 From: Abdullah Atta Date: Wed, 5 Aug 2026 22:16:56 +0500 Subject: [PATCH] common: avoid long lived mail client --- Streetwriters.Common/Services/EmailSender.cs | 47 +++++++++----------- 1 file changed, 22 insertions(+), 25 deletions(-) diff --git a/Streetwriters.Common/Services/EmailSender.cs b/Streetwriters.Common/Services/EmailSender.cs index 63f43c9..5576439 100644 --- a/Streetwriters.Common/Services/EmailSender.cs +++ b/Streetwriters.Common/Services/EmailSender.cs @@ -14,9 +14,8 @@ using Streetwriters.Common.Models; namespace Streetwriters.Common.Services { - public class EmailSender : IEmailSender, IAsyncDisposable + public class EmailSender : IEmailSender { - private readonly SmtpClient mailClient = new(); private readonly ILogger logger; public EmailSender(ILogger logger) @@ -32,27 +31,25 @@ namespace Streetwriters.Common.Services Dictionary? attachments = null ) { - if (!mailClient.IsConnected) + using var mailClient = new SmtpClient(); + + if (int.TryParse(Common.Constants.SMTP_PORT, out int port)) { - if (int.TryParse(Common.Constants.SMTP_PORT, out int port)) - { - await mailClient.ConnectAsync( - Common.Constants.SMTP_HOST, - port, - MailKit.Security.SecureSocketOptions.Auto - ); - } - else - { - throw new InvalidDataException("SMTP_PORT is not a valid integer value."); - } + await mailClient.ConnectAsync( + Common.Constants.SMTP_HOST, + port, + MailKit.Security.SecureSocketOptions.Auto + ); + } + else + { + throw new InvalidDataException("SMTP_PORT is not a valid integer value."); } - if (!mailClient.IsAuthenticated) - await mailClient.AuthenticateAsync( - Common.Constants.SMTP_USERNAME, - Common.Constants.SMTP_PASSWORD - ); + await mailClient.AuthenticateAsync( + Common.Constants.SMTP_USERNAME, + Common.Constants.SMTP_PASSWORD + ); var message = new MimeMessage(); message.From.Add(new MailboxAddress(from.DisplayName, from.Address)); @@ -70,6 +67,11 @@ namespace Streetwriters.Common.Services ); await mailClient.SendAsync(message); + + if (mailClient.IsConnected) + { + await mailClient.DisconnectAsync(true); + } } private async Task GetEmailBodyAsync( @@ -129,10 +131,5 @@ namespace Streetwriters.Common.Services } } - async ValueTask IAsyncDisposable.DisposeAsync() - { - await mailClient.DisconnectAsync(true); - mailClient.Dispose(); - } } }