aboutsummaryrefslogtreecommitdiffstats
path: root/server/src/Services/MailService.cs
blob: c08cb8446d67ce4c8482cb5f9440e42038fe9e94 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
namespace IOL.GreatOffice.Api.Services;

public class MailService
{
    private readonly ILogger<MailService> _logger;
    private static string _emailHost;
    private static int _emailPort;
    private static string _emailUser;
    private static string _emailPassword;

    public MailService(VaultService vaultService, ILogger<MailService> logger) {
        var configuration = vaultService.GetCurrentAppConfiguration();
        _logger = logger;
        _emailHost = configuration.SMTP_HOST;
        _emailPort = Convert.ToInt32(configuration.SMTP_PORT);
        _emailUser = configuration.SMTP_USER;
        _emailPassword = configuration.SMTP_PASSWORD;
    }

    /// <summary>
    /// Send an email.
    /// </summary>
    /// <param name="message"></param>
    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
            });
        
        _logger.LogDebug("SmtpClient was instansiated with the following configuration\n" + configurationString);

        smtpClient.Send(message);
    }
}