Files
Umbraco-CMS/src/Umbraco.Infrastructure/Mail/BasicSmtpEmailSenderClient.cs
kasparboelkjeldsen 7cc8f844f7 Support for SMTP OAuth authentication through easier IEmailSenderClient implementation (#17484)
* Implement IEmailSenderClient interface and implementation

In an effort to support oauth 2 and other schemes, we extract a emailsenderclient interface, allowing to replace default smtp client with one that fits the usecase, without having to implement all of Umbracos logic that builds the mimemessage

* fix test

* Documentation

* EmailMessageExtensions public, use EmailMessage in interface and impl.

* move mimemessage into implementation

* revert EmailMessageExtensions back to internal

* use StaticServiceProvider to avoid breaking change

* Fix test after changing constructor

* revert constructor change and add new constructor an obsoletes

* Moved a paranthesis so it will build in release-mode

(cherry picked from commit bff321e6f5)
2024-11-19 08:49:35 +01:00

51 lines
1.7 KiB
C#

using System.Net.Mail;
using Microsoft.Extensions.Options;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Models.Email;
using Umbraco.Cms.Infrastructure.Extensions;
using Umbraco.Cms.Infrastructure.Mail.Interfaces;
using SecureSocketOptions = MailKit.Security.SecureSocketOptions;
using SmtpClient = MailKit.Net.Smtp.SmtpClient;
namespace Umbraco.Cms.Infrastructure.Mail
{
/// <summary>
/// A basic SMTP email sender client using MailKits SMTP client.
/// </summary>
public class BasicSmtpEmailSenderClient : IEmailSenderClient
{
private readonly GlobalSettings _globalSettings;
public BasicSmtpEmailSenderClient(IOptionsMonitor<GlobalSettings> globalSettings)
{
_globalSettings = globalSettings.CurrentValue;
}
public async Task SendAsync(EmailMessage message)
{
using var client = new SmtpClient();
await client.ConnectAsync(
_globalSettings.Smtp!.Host,
_globalSettings.Smtp.Port,
(SecureSocketOptions)(int)_globalSettings.Smtp.SecureSocketOptions);
if (!string.IsNullOrWhiteSpace(_globalSettings.Smtp.Username) &&
!string.IsNullOrWhiteSpace(_globalSettings.Smtp.Password))
{
await client.AuthenticateAsync(_globalSettings.Smtp.Username, _globalSettings.Smtp.Password);
}
var mimeMessage = message.ToMimeMessage(_globalSettings.Smtp!.From);
if (_globalSettings.Smtp.DeliveryMethod == SmtpDeliveryMethod.Network)
{
await client.SendAsync(mimeMessage);
}
else
{
client.Send(mimeMessage);
}
}
}
}