using System; using System.Net; using System.Threading.Tasks; using MailKit.Net.Smtp; using MailKit.Security; using MimeKit; using MimeKit.Text; using NLog; using gswi.Configuration; using gswi.Model.Filters; using gswi.SMTP.Interface; using gswi.SMTP.Model; namespace gswi.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}

Dies ist eine Automatische E-Mail.
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"); } } } } }