summaryrefslogtreecommitdiffstats
path: root/server/src/Services/MailService.cs
blob: eaff764943b2c82438769a2e8558e15a4d0cd635 (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
50
51
52
53
54
55
using Microsoft.Extensions.Options;

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;

	/// <summary>
	/// Provides methods to send email.
	/// </summary>
	/// <param name="configuration"></param>
	/// <param name="logger"></param>
	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 {
																   Host = smtpClient.Host,
																   EnableSsl = smtpClient.EnableSsl,
																   Port = 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);
	}
}