feat: add configurable SMTP settings

This commit is contained in:
Oliver Booth 2024-10-20 04:02:54 +01:00
parent fdf8f9c32d
commit ee8a2cb569
Signed by: oliverbooth
GPG Key ID: 2A862C3F46178E8E

View File

@ -11,6 +11,7 @@ public class ContactController : Controller
private readonly ILogger<ContactController> _logger; private readonly ILogger<ContactController> _logger;
private readonly IConfiguration _configuration; private readonly IConfiguration _configuration;
private readonly IConfigurationSection _destination; private readonly IConfigurationSection _destination;
private readonly IConfigurationSection _sender;
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="ContactController" /> class. /// Initializes a new instance of the <see cref="ContactController" /> class.
@ -21,7 +22,10 @@ public class ContactController : Controller
{ {
_logger = logger; _logger = logger;
_configuration = configuration; _configuration = configuration;
_destination = configuration.GetSection("Mail").GetSection("Destination");
IConfigurationSection mailConfiguration = configuration.GetSection("Mail");
_destination = mailConfiguration.GetSection("Destination");
_sender = mailConfiguration.GetSection("Sender");
} }
[HttpGet("{_?}")] [HttpGet("{_?}")]
@ -57,7 +61,8 @@ public class ContactController : Controller
{ {
await sender.WriteEmail await sender.WriteEmail
.To("Oliver Booth", _destination.Get<string>()) .To("Oliver Booth", _destination.Get<string>())
.From(name, email) .From(name, _sender.Get<string>())
.ReplyTo(email)
.Subject($"[Contact via Website] {subject}") .Subject($"[Contact via Website] {subject}")
.BodyText(message) .BodyText(message)
.SendAsync(); .SendAsync();
@ -79,8 +84,9 @@ public class ContactController : Controller
string? mailServer = mailSection.GetSection("Server").Value; string? mailServer = mailSection.GetSection("Server").Value;
string? mailUsername = mailSection.GetSection("Username").Value; string? mailUsername = mailSection.GetSection("Username").Value;
string? mailPassword = mailSection.GetSection("Password").Value; string? mailPassword = mailSection.GetSection("Password").Value;
ushort port = mailSection.GetSection("Port").Get<ushort>();
var sender = SmtpSender.Create(mailServer); var sender = SmtpSender.Create(mailServer, port);
sender.SetCredential(mailUsername, mailPassword); sender.SetCredential(mailUsername, mailPassword);
return sender; return sender;
} }