From d852bb69dbce0126a0d8ba660b9931ea7cc062c3 Mon Sep 17 00:00:00 2001 From: ivarlovlie Date: Fri, 25 Nov 2022 16:32:05 +0900 Subject: feat: Suppress and log exceptions when sending email --- code/api/src/Services/MailService.cs | 47 +++++++++++++++++++----------------- 1 file changed, 25 insertions(+), 22 deletions(-) diff --git a/code/api/src/Services/MailService.cs b/code/api/src/Services/MailService.cs index b55b48f..1e565f5 100644 --- a/code/api/src/Services/MailService.cs +++ b/code/api/src/Services/MailService.cs @@ -22,28 +22,31 @@ public class MailService /// /// public void SendMail(MailMessage message) { - using var smtpClient = new SmtpClient { - Host = _emailHost, - EnableSsl = _emailPort == 587, - Port = _emailPort, - Credentials = new NetworkCredential { - UserName = _emailUser, - Password = _emailPassword, - } - }; - var configurationString = JsonSerializer.Serialize(new { - smtpClient.Host, - smtpClient.EnableSsl, - smtpClient.Port, - UserName = _emailUser.HasValue() ? "**REDACTED**" : "**MISSING**", - Password = _emailPassword.HasValue() ? "**REDACTED**" : "**MISSING**", - }, - new JsonSerializerOptions { - WriteIndented = true - }); + try { + using var smtpClient = new SmtpClient { + Host = _emailHost, + EnableSsl = _emailPort == 587, + Port = _emailPort, + Credentials = new NetworkCredential { + UserName = _emailUser, + Password = _emailPassword, + } + }; + var configurationString = JsonSerializer.Serialize(new { + smtpClient.Host, + smtpClient.EnableSsl, + smtpClient.Port, + UserName = _emailUser.HasValue() ? "**REDACTED**" : "**MISSING**", + Password = _emailPassword.HasValue() ? "**REDACTED**" : "**MISSING**", + }, + new JsonSerializerOptions { + WriteIndented = true + }); - _logger.LogDebug("SmtpClient was instansiated with the following configuration\n" + configurationString); - - smtpClient.Send(message); + _logger.LogDebug("SmtpClient was instansiated with the following configuration\n" + configurationString); + smtpClient.Send(message); + } catch (Exception e) { + _logger.LogError(e, "An exception occured while trying to send an email"); + } } } \ No newline at end of file -- cgit v1.3