Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 33 additions & 20 deletions Services/Helpers/MailService/SMTPEmailService.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,29 @@
using System;
using System;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MimeKit;
using Models.Helpers;

namespace Services.Helpers.MailService;

public class SmtpMailService(IOptions<AppSettings> json) : IMailService
namespace Services.Helpers.MailService
{
public void SendEmail(string toEmail, string message, string fromTitle = "", string Subject = "")
public class SmtpMailService : IMailService
{
var options = json.Value.Smtp;
private readonly AppSettings _appSettings; // Dependency injected settings
private readonly ILogger<SmtpMailService> _logger; // Dependency injected logger for better logging

// Constructor with dependency injection
public SmtpMailService(IOptions<AppSettings> settings, ILogger<SmtpMailService> logger)
{
_appSettings = settings.Value; // Assign settings from IOptions
_logger = logger; // Assign logger
}

// Asynchronous method to send email
public async Task SendEmailAsync(string toEmail, string message, string fromTitle = "", string subject = "")
{
var options = _appSettings.Smtp;
toEmail = toEmail.ToLower();
var email = new MimeMessage();
var from = new MailboxAddress(fromTitle, options.Email);
Expand All @@ -19,29 +32,29 @@ public void SendEmail(string toEmail, string message, string fromTitle = "", str
var to = MailboxAddress.Parse(toEmail);
email.To.Add(to);

email.Subject = Subject;
email.Subject = subject;

// Supporting HTML content in the body
var bodyBuilder = new BodyBuilder
{
TextBody = message
TextBody = message,
HtmlBody = $"<html><body>{message}</body></html>"
};
email.Body = bodyBuilder.ToMessageBody();
var client = new SmtpClient();

using var client = new SmtpClient(); // Using statement to ensure disposal
try
{
client.Connect(options.Host, options.Port, options.UseSsl);
client.Authenticate(options.Email, options.Password);
client.Send(email);
client.Disconnect(true);
await client.ConnectAsync(options.Host, options.Port, options.UseSsl); // Asynchronous connection
await client.AuthenticateAsync(options.Email, options.Password); // Asynchronous authentication
await client.SendAsync(email); // Asynchronous send
await client.DisconnectAsync(true); // Asynchronous disconnect
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
finally
{
client.Dispose();
_logger.LogError("Failed to send email: {ExceptionMessage}", e.Message); // Detailed logging
throw new ApplicationException("Error in sending email", e); // Throwing an application-specific exception
}
}
}
}
}