web-app-template/backend/app/app.SMTP.Service/SMTPClientImpl.cs

80 lines
2.8 KiB
C#
Raw Permalink Normal View History

2022-02-20 13:43:25 +01:00
using System;
using System.Net;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
using MimeKit.Text;
using NLog;
using app.Configuration;
using app.Model.Filters;
using app.SMTP.Interface;
using app.SMTP.Model;
namespace app.SMTP.Service
{
public class SMTPClientImpl : ISMTPClient
{
private readonly EMailSettings _emailSettings;
private static Logger _logger = LogManager.GetCurrentClassLogger();
public SMTPClientImpl(EMailSettings emailSettings)
{
this._emailSettings = emailSettings;
}
public async Task SendEmailAsync(EMail email)
{
var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress(_emailSettings.FromName, _emailSettings.FromAddress));
emailMessage.To.Add(new MailboxAddress("", email.Receiver));
emailMessage.Subject = email.Subject;
emailMessage.Body = new TextPart(TextFormat.Html) { Text = $"{email.Message}<br><br>Dies ist eine Automatische E-Mail.<br>Gesendet von Login counter @ {System.Net.Dns.GetHostName()}" };
using (var client = new SmtpClient())
{
client.Timeout = 30000;
try
{
await client.ConnectAsync(_emailSettings.MailServerAddress, _emailSettings.MailServerPort, SecureSocketOptions.Auto).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.Error(ex);
throw new ServiceException(ServiceErrorCode.ConnectionFailed, "Connection to mail server failed");
}
try
{
await client.AuthenticateAsync(new NetworkCredential(_emailSettings.Username, _emailSettings.Credentials));
}
catch (Exception ex)
{
_logger.Error(ex);
throw new ServiceException(ServiceErrorCode.InvalidUser, "Authentification to mail server failed");
}
try
{
await client.SendAsync(emailMessage).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.Error(ex);
throw new ServiceException(ServiceErrorCode.MailError, "Unable to send email");
}
try
{
await client.DisconnectAsync(true).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.Error(ex);
throw new ServiceException(ServiceErrorCode.ConnectionFailed, "Unable to disconnect from mail server");
}
}
}
}
}