isn/src/isnd/Services/EmailSender.cs

57 lines
1.9 KiB
C#

3 years ago
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Hosting;
using MailKit.Net.Smtp;
using MimeKit;
using System;
using isnd.Interfaces;
using isnd.Entities;
namespace isnd.Services
{
public class EmailSender : IEmailSender, IMailer
{
public EmailSender(IOptions<SmtpSettings> smtpSettings,
2 years ago
IWebHostEnvironment env)
3 years ago
{
Options = smtpSettings.Value;
Env = env;
}
public SmtpSettings Options { get; } //set only via Secret Manager
2 years ago
public IWebHostEnvironment Env { get; }
3 years ago
public Task SendEmailAsync(string email, string subject, string message)
{
return Execute(Options.SenderName, subject, message, email);
}
public async Task Execute(string name, string subject, string message, string email)
{
await SendMailAsync(name, email, subject, message);
}
2 years ago
public async Task SendMailAsync(string name, string email, string subject, string body)
3 years ago
{
try {
var message = new MimeMessage();
message.From.Add(new MailboxAddress(Options.SenderName, Options.SenderEMail));
message.To.Add(new MailboxAddress(name??email, email));
message.Body = new TextPart("html") { Text = body };
using (var client = new SmtpClient())
{
client.ServerCertificateValidationCallback = (s,c,h,e)=>true;
await client.ConnectAsync(Options.Server);
await client.AuthenticateAsync(Options.UserName, Options.Password);
await client.SendAsync(message);
await client.DisconnectAsync(true);
}
}
catch (Exception e)
{
throw new InvalidOperationException(e.Message);
}
}
}
}