yavsc/src/Yavsc.Server/Services/MailSender.cs

192 lines
7.4 KiB
C#
Raw Normal View History

#nullable enable annotations
using MailKit.Net.Smtp;
using MailKit.Security;
using Microsoft.Extensions.Logging;
2023-03-19 17:57:55 +00:00
using Microsoft.Extensions.Options;
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;
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;
using System.Text.RegularExpressions;
2025-03-02 16:53:36 +00:00
using System.Web;
namespace Yavsc.Services
{
2025-09-07 17:43:13 +01:00
public class MailSender : IEmailSender<ApplicationUser>, IEmailSender, ITrueEmailSender
{
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;
private readonly ISmtpClientFactory _smtpClientFactory;
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,
IStringLocalizer<MailSender> localizer,
ISmtpClientFactory smtpClientFactory
)
{
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>();
_smtpClientFactory = smtpClientFactory;
}
2025-03-02 16:53:36 +00:00
public Task SendConfirmationLinkAsync(ApplicationUser user, string email, string confirmationLink)
{
throw new NotImplementedException();
}
/// <summary>
///
/// </summary>
/// <param name="googleSettings"></param>
/// <param name="registrationId"></param>
/// <param name="ev"></param>
/// <returns>a MessageWithPayloadResponse,
/// <c>bool somethingsent = (response.failure == 0 &amp;&amp; response.success > 0)</c>
/// </returns>
2026-04-20 00:35:51 +01:00
public Task SendEmailAsync(string email, string subject, string htmlMessage)
{
2026-08-29 14:34:43 +01:00
return SendEmailAsync(null, email, subject, htmlMessage);
2023-04-05 22:29:40 +01:00
}
internal static MailboxAddress BuildMailboxAddress(string? displayName, string? rawAddress)
2023-04-05 22:29:40 +01:00
{
if (string.IsNullOrWhiteSpace(rawAddress))
{
throw new FormatException("Email address is empty.");
}
var candidate = rawAddress.Trim();
if (candidate.Contains('<') || candidate.Contains('>'))
{
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
{
candidate = emailMatch.Value;
2023-04-05 22:29:40 +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
public async Task<string> SendEmailAsync(string name, string email, string subject, string htmlMessage)
{
try
{
logger.LogInformation($"SendEmail for {email} : {subject}");
if (string.IsNullOrWhiteSpace(siteSettings?.Owner?.EMail)
|| string.IsNullOrWhiteSpace(smtpSettings?.Host))
{
logger.LogError("Email not sent: mail configuration is incomplete (Site:Owner:EMail and Smtp:Host are required). To={To}, Subject={Subject}", email, subject);
return string.Empty;
}
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
);
using Yavsc.Interfaces.ISmtpClient sc = _smtpClientFactory.CreateClient();
{
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);
return string.Empty;
}
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;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to send email. To={To}, Subject={Subject}", email, subject);
throw;
}
}
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)
{
Split Site:Audience into Site:ExternalUrl + Site:CorsAllowedOrigins The Site:Audience setting was conflating two distinct concepts: an OAuth JWT audience (a single resource identifier) and a CORS allow-list (an array of origins). Collapsing them caused several latent bugs: - OAuth/JWT validation expected a single string while CORS WithOrigins accepts an array. - Password-reset callback URLs and OAuth client RedirectUri/Origin were being built from what was meant to be an audience identifier, not a base URL. - Yavsc.Org's main CORS policy was hardcoded to '*', with no way to restrict it without code changes. Changes: - SiteSettings.Audience (string) replaced with CorsAllowedOrigins (IList<string>). - OAuth JWT Authority still reads Site:Authority; Audience now reads Site:ExternalUrl (Org only; Api/Blogs use ValidateAudience=false). - MailSender and AccountController build reset-callback URLs from Site:ExternalUrl. - ClientController uses Site:ExternalUrl for OAuth RedirectUri/Origin defaults on newly created clients. - Yavsc.Api and Yavsc.Blogs now read CORS origins from Site:CorsAllowedOrigins instead of hardcoded URLs. Add shared AddYavscCors / AddYavscJwtBearer extension methods in Yavsc.Server/Helpers/ServiceExtensions.cs to enforce a single configuration contract across all runtime services (Api, Blogs, Org). Fails closed when CorsAllowedOrigins is empty; fails fast at startup when Site:Authority is missing. Remove obsolete ConfigurationHelpers.GetAudience (no remaining callers). Local appsettings-*.json files (which carry deployment-specific values and are gitignored) must be updated to add Site:CorsAllowedOrigins.
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
}
}
}