2026-09-06 16:11:37 +01:00
#nullable enable annotations
2026-08-29 17:21:40 +01:00
using MailKit.Net.Smtp ;
2018-07-15 06:47:41 +02:00
using MailKit.Security ;
using Microsoft.Extensions.Logging ;
2023-03-19 17:57:55 +00:00
using Microsoft.Extensions.Options ;
2018-07-15 06:47:41 +02:00
using MimeKit ;
2025-03-02 16:53:36 +00:00
using Microsoft.AspNetCore.Identity ;
2023-04-05 22:29:40 +01:00
using Yavsc.Interface ;
2026-06-22 01:44:24 +01:00
using Yavsc.Interfaces ;
2023-04-05 22:29:40 +01:00
using Yavsc.Settings ;
2025-03-02 16:53:36 +00:00
using Yavsc.Models ;
using Microsoft.AspNetCore.Identity.UI.Services ;
using Microsoft.Extensions.Localization ;
2026-08-29 15:36:36 +01:00
using System.Text.RegularExpressions ;
2025-03-02 16:53:36 +00:00
using System.Web ;
2018-07-15 06:47:41 +02:00
namespace Yavsc.Services
{
2025-09-07 17:43:13 +01:00
public class MailSender : IEmailSender < ApplicationUser > , IEmailSender , ITrueEmailSender
2018-07-15 06:47:41 +02:00
{
2026-06-22 01:44:24 +01:00
2025-08-31 18:27:53 +01:00
private readonly IStringLocalizer < MailSender > localizer ;
2020-09-12 01:11:30 +01:00
readonly SiteSettings siteSettings ;
readonly SmtpSettings smtpSettings ;
2023-03-19 16:02:50 +00:00
private readonly ILogger logger ;
2026-06-22 01:44:24 +01:00
private readonly ISmtpClientFactory _smtpClientFactory ;
2018-07-15 06:47:41 +02:00
public MailSender (
2025-09-07 17:43:13 +01:00
IOptions < SiteSettings > sitesOptions ,
2023-03-19 16:02:50 +00:00
IOptions < SmtpSettings > smtpOptions ,
2025-08-31 18:27:53 +01:00
ILoggerFactory loggerFactory ,
2026-06-22 01:44:24 +01:00
IStringLocalizer < MailSender > localizer ,
ISmtpClientFactory smtpClientFactory
2018-07-15 06:47:41 +02:00
)
{
2025-03-02 16:53:36 +00:00
this . localizer = localizer ;
2023-04-05 22:29:40 +01:00
siteSettings = sitesOptions . Value ;
smtpSettings = smtpOptions . Value ;
2023-03-19 16:02:50 +00:00
logger = loggerFactory . CreateLogger < MailSender > ( ) ;
2026-06-22 01:44:24 +01:00
_smtpClientFactory = smtpClientFactory ;
2018-07-15 06:47:41 +02:00
}
2025-03-02 16:53:36 +00:00
public Task SendConfirmationLinkAsync ( ApplicationUser user , string email , string confirmationLink )
{
throw new NotImplementedException ( ) ;
}
2018-07-15 06:47:41 +02:00
/// <summary>
///
/// </summary>
/// <param name="googleSettings"></param>
/// <param name="registrationId"></param>
/// <param name="ev"></param>
/// <returns>a MessageWithPayloadResponse,
/// <c>bool somethingsent = (response.failure == 0 && response.success > 0)</c>
/// </returns>
2026-04-20 00:35:51 +01:00
public Task SendEmailAsync ( string email , string subject , string htmlMessage )
2018-07-15 06:47:41 +02:00
{
2026-08-29 14:34:43 +01:00
return SendEmailAsync ( null , email , subject , htmlMessage ) ;
2023-04-05 22:29:40 +01:00
}
2026-08-29 15:36:36 +01:00
internal static MailboxAddress BuildMailboxAddress ( string? displayName , string? rawAddress )
2023-04-05 22:29:40 +01:00
{
2026-08-29 15:36:36 +01:00
if ( string . IsNullOrWhiteSpace ( rawAddress ) )
2018-07-15 06:47:41 +02:00
{
2026-08-29 15:36:36 +01:00
throw new FormatException ( "Email address is empty." ) ;
}
var candidate = rawAddress . Trim ( ) ;
if ( candidate . Contains ( '<' ) | | candidate . Contains ( '>' ) )
2018-07-15 06:47:41 +02:00
{
2026-08-29 15:36:36 +01:00
var emailMatch = Regex . Match ( candidate ,
@"[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}" ,
RegexOptions . CultureInvariant | RegexOptions . IgnoreCase ) ;
if ( emailMatch . Success )
2025-09-07 17:43:13 +01:00
{
2026-08-29 15:36:36 +01:00
candidate = emailMatch . Value ;
2023-04-05 22:29:40 +01:00
}
2026-08-29 15:36:36 +01:00
else
{
candidate = candidate . Trim ( '<' , '>' , '"' , '\'' ) ;
}
}
candidate = candidate . Trim ( '"' , '\'' , '<' , '>' , ' ' ) ;
candidate = candidate . Replace ( " " , string . Empty ) ;
if ( ! MailboxAddress . TryParse ( candidate , out var parsedAddress ) )
{
throw new FormatException ( $"Invalid email address '{rawAddress}'." ) ;
}
var safeName = string . IsNullOrWhiteSpace ( displayName )
? parsedAddress . Name
: displayName . Trim ( ) ;
return new MailboxAddress ( safeName ? ? string . Empty , parsedAddress . Address ) ;
}
2025-09-07 17:43:13 +01:00
2026-08-29 15:36:36 +01:00
public async Task < string > SendEmailAsync ( string name , string email , string subject , string htmlMessage )
{
try
{
logger . LogInformation ( $"SendEmail for {email} : {subject}" ) ;
MimeMessage msg = new ( ) ;
msg . From . Add ( BuildMailboxAddress ( siteSettings . Owner . Name , siteSettings . Owner . EMail ) ) ;
msg . To . Add ( BuildMailboxAddress ( name , email ) ) ;
TextPart text ;
msg . Body = text = new TextPart ( "html" )
{
Text = $"<html><body>{htmlMessage}</body></html>"
} ;
msg . Subject = subject ;
msg . MessageId = MimeKit . Utils . MimeUtils . GenerateMessageId (
siteSettings . Authority
) ;
2026-08-29 17:21:40 +01:00
using Yavsc.Interfaces.ISmtpClient sc = _smtpClientFactory . CreateClient ( ) ;
2026-08-29 15:36:36 +01:00
{
sc . Timeout = 30000 ;
sc . Connect (
smtpSettings . Host ,
smtpSettings . Port ,
SecureSocketOptions . Auto
) ;
if ( smtpSettings . UserName ! = null )
{
sc . Authenticate ( smtpSettings . UserName , smtpSettings . Password ) ;
}
await sc . SendAsync ( msg ) ;
logger . LogInformation ( $"Sent : {msg.MessageId}" ) ;
sc . Disconnect ( true ) ;
}
return msg . MessageId ;
}
catch ( FormatException ex )
{
logger . LogError ( ex , "Refusing to send email because the recipient or sender address is malformed. To={To}, From={From}" , email , siteSettings . Owner . EMail ) ;
2026-09-20 21:06:02 +01:00
logger . LogError ( ex . Message ) ;
if ( ex . InnerException ! = null )
logger . LogError ( ex . InnerException . Message ) ;
2026-08-29 15:36:36 +01:00
return string . Empty ;
}
2026-08-29 17:21:40 +01:00
catch ( SmtpCommandException ex )
{
logger . LogError ( ex , "SMTP rejected the recipient or sender address. To={To}, Subject={Subject}, Status={Status}, Error={Error}" , email , subject , ex . StatusCode , ex . Message ) ;
return string . Empty ;
}
2026-08-29 15:36:36 +01:00
catch ( Exception ex )
{
logger . LogError ( ex , "Failed to send email. To={To}, Subject={Subject}" , email , subject ) ;
throw ;
2018-07-15 06:47:41 +02:00
}
}
2025-03-02 16:53:36 +00:00
2025-07-16 00:47:50 +01:00
public void SendEmailFromCriteria ( string Criteria )
{
throw new NotImplementedException ( ) ;
}
2025-03-02 16:53:36 +00:00
public async Task SendPasswordResetCodeAsync ( ApplicationUser user , string email , string resetCode )
{
2026-06-19 13:15:21 +01:00
var callbackUrl = siteSettings . ExternalUrl + "/Account/ResetPassword/" +
2025-03-02 16:53:36 +00:00
HttpUtility . UrlEncode ( user . Id ) + "/" + HttpUtility . UrlEncode ( resetCode ) ;
2025-09-07 17:43:13 +01:00
await SendEmailAsync ( user . UserName , user . Email ,
2025-03-02 16:53:36 +00:00
localizer [ "Reset Password" ] ,
localizer [ "Please reset your password by " ] + " <a href=\"" +
callbackUrl + "\" >following this link</a>" ) ;
throw new NotImplementedException ( ) ;
}
public async Task SendPasswordResetLinkAsync ( ApplicationUser user , string email , string resetLink )
{
2025-09-07 17:43:13 +01:00
await SendEmailAsync ( user . UserName , user . Email ,
localizer [ "Reset Password" ] ,
localizer [ "Please reset your password by " ] + " <a href=\"" +
resetLink + "\" >following this link</a>" ) ;
2025-03-02 16:53:36 +00:00
}
2018-07-15 06:47:41 +02:00
}
2018-11-19 17:39:03 +01:00
}