2021-12-31 16:59:02 +09:00
|
|
|
using System.Threading;
|
|
|
|
using System.Threading.Tasks;
|
2022-03-11 10:17:50 +01:00
|
|
|
using BTCPayServer.Client.Models;
|
2021-12-31 16:59:02 +09:00
|
|
|
using MailKit.Net.Smtp;
|
|
|
|
using MimeKit;
|
2017-09-27 14:18:09 +09:00
|
|
|
|
|
|
|
namespace BTCPayServer.Services.Mails
|
|
|
|
{
|
2022-05-23 03:00:34 -07:00
|
|
|
public class EmailSettings : EmailSettingsData
|
2017-09-27 14:18:09 +09:00
|
|
|
{
|
2021-12-15 21:30:46 +09:00
|
|
|
public bool IsComplete()
|
2017-10-27 17:53:04 +09:00
|
|
|
{
|
2022-05-23 03:00:34 -07:00
|
|
|
return !string.IsNullOrWhiteSpace(Server) && Port is int;
|
2017-10-27 17:53:04 +09:00
|
|
|
}
|
2017-09-27 14:18:09 +09:00
|
|
|
|
2021-12-15 21:30:46 +09:00
|
|
|
public MimeMessage CreateMailMessage(MailboxAddress to, string subject, string message, bool isHtml)
|
2018-05-05 01:42:42 +09:00
|
|
|
{
|
2021-12-15 21:30:46 +09:00
|
|
|
var bodyBuilder = new BodyBuilder();
|
|
|
|
if (isHtml)
|
2018-05-05 01:42:42 +09:00
|
|
|
{
|
2021-12-15 21:30:46 +09:00
|
|
|
bodyBuilder.HtmlBody = message;
|
2018-05-05 01:42:42 +09:00
|
|
|
}
|
2021-12-15 21:30:46 +09:00
|
|
|
else
|
2019-07-14 22:45:14 +09:00
|
|
|
{
|
2021-12-15 21:30:46 +09:00
|
|
|
bodyBuilder.TextBody = message;
|
|
|
|
}
|
|
|
|
|
|
|
|
return new MimeMessage(
|
2021-12-31 16:59:02 +09:00
|
|
|
from: new[] { new MailboxAddress(From, !string.IsNullOrWhiteSpace(FromDisplay) ? From : FromDisplay) },
|
2021-12-15 21:30:46 +09:00
|
|
|
to: new[] { to },
|
|
|
|
subject,
|
|
|
|
bodyBuilder.ToMessageBody());
|
2019-07-14 22:45:14 +09:00
|
|
|
}
|
|
|
|
|
2021-12-15 21:30:46 +09:00
|
|
|
public async Task<SmtpClient> CreateSmtpClient()
|
2017-10-27 17:53:04 +09:00
|
|
|
{
|
2021-12-15 21:30:46 +09:00
|
|
|
SmtpClient client = new SmtpClient();
|
|
|
|
using var connectCancel = new CancellationTokenSource(10000);
|
|
|
|
try
|
|
|
|
{
|
2021-12-29 18:24:24 +09:00
|
|
|
if (Extensions.IsLocalNetwork(Server))
|
|
|
|
{
|
|
|
|
client.CheckCertificateRevocation = false;
|
|
|
|
#pragma warning disable CA5359 // Do Not Disable Certificate Validation
|
|
|
|
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
|
|
|
|
#pragma warning restore CA5359 // Do Not Disable Certificate Validation
|
|
|
|
}
|
2021-12-15 21:30:46 +09:00
|
|
|
await client.ConnectAsync(Server, Port.Value, MailKit.Security.SecureSocketOptions.Auto, connectCancel.Token);
|
2022-05-23 03:00:34 -07:00
|
|
|
if ((client.Capabilities & SmtpCapabilities.Authentication) != 0)
|
|
|
|
await client.AuthenticateAsync(Login ?? string.Empty, Password ?? string.Empty, connectCancel.Token);
|
2021-12-15 21:30:46 +09:00
|
|
|
}
|
|
|
|
catch
|
|
|
|
{
|
|
|
|
client.Dispose();
|
|
|
|
throw;
|
|
|
|
}
|
2017-10-27 17:53:04 +09:00
|
|
|
return client;
|
|
|
|
}
|
|
|
|
}
|
2017-09-27 14:18:09 +09:00
|
|
|
}
|