btcpayserver/BTCPayServer/Services/Mails/EmailSender.cs

48 lines
1.6 KiB
C#
Raw Normal View History

2020-06-28 21:44:35 -05:00
using System;
2017-09-27 14:18:09 +09:00
using System.Net.Mail;
2017-09-13 15:47:34 +09:00
using System.Threading.Tasks;
2020-06-28 17:55:27 +09:00
using BTCPayServer.Logging;
using Microsoft.Extensions.Logging;
using NBitcoin;
2017-09-13 15:47:34 +09:00
namespace BTCPayServer.Services.Mails
2017-09-13 15:47:34 +09:00
{
2019-01-06 15:53:37 +01:00
public abstract class EmailSender : IEmailSender
{
readonly IBackgroundJobClient _JobClient;
2019-01-06 15:53:37 +01:00
public EmailSender(IBackgroundJobClient jobClient)
{
2019-01-06 15:53:37 +01:00
_JobClient = jobClient ?? throw new ArgumentNullException(nameof(jobClient));
}
2019-01-06 15:53:37 +01:00
public void SendEmail(string email, string subject, string message)
{
_JobClient.Schedule(async (cancellationToken) =>
{
2019-01-06 15:53:37 +01:00
var emailSettings = await GetEmailSettings();
if (emailSettings?.IsComplete() != true)
{
Logs.Configuration.LogWarning("Should have sent email, but email settings are not configured");
return;
}
using (var smtp = emailSettings.CreateSmtpClient())
2019-01-06 15:53:37 +01:00
{
var mail = emailSettings.CreateMailMessage(new MailAddress(email), subject, message);
mail.IsBodyHtml = true;
try
{
await smtp.SendMailAsync(mail).WithCancellation(cancellationToken);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
smtp.SendAsyncCancel();
}
}
2020-06-28 17:55:27 +09:00
}, TimeSpan.Zero);
}
2019-01-06 15:53:37 +01:00
public abstract Task<EmailSettings> GetEmailSettings();
}
2017-09-13 15:47:34 +09:00
}