using MailKit.Net.Smtp; using Massmailer.Shared.Model; using MimeKit; using System; using System.Threading.Tasks; namespace Massmailer.Shared.Logic { public class Mailer : IMailer { private readonly SmtpSettings smtpSettings; public Mailer(SmtpSettings smtpSettings) { this.smtpSettings = smtpSettings; } public async Task SendMailAsync(string email, string subject, string body) { try { var message = new MimeMessage(); message.From.Add(new MailboxAddress(this.smtpSettings.SenderName, this.smtpSettings.SenderEmail)); message.To.Add(new MailboxAddress(email, email)); message.Subject = subject; message.Body = new TextPart("html") { Text = body }; using (var client = new SmtpClient()) { client.ServerCertificateValidationCallback = (s, c, h, e) => true; await client.ConnectAsync(this.smtpSettings.Server, this.smtpSettings.Port, this.smtpSettings.UseSsl); await client.AuthenticateAsync(this.smtpSettings.Username, this.smtpSettings.Password); await client.SendAsync(message); await client.DisconnectAsync(true); } } catch (Exception ex) { throw new InvalidOperationException(ex.Message); } } } }