In ASP.NET Core 2.1 I have a class to send e-mail that uses IOptions interface as shown bellow:
public class Email
{
private readonly ManuelaIbiEmail manuelaIbiEmail;
public Email(IOptions<ManuelaIbiEmail> manuelaIbiEmail)
{
this.manuelaIbiEmail.Username = manuelaIbiEmail.Value.Username;
this.manuelaIbiEmail.Password = manuelaIbiEmail.Value.Password;
}
public async Task SendAsync(Contato contato)
{
var smtpClient = new SmtpClient
{
Host = "smtp.sendgrid.net",
Port = 587,
EnableSsl = true,
Credentials = new NetworkCredential(manuelaIbiEmail.Username, manuelaIbiEmail.Password)
};
using (var message = new MailMessage(contato.Email, "manuelaibi66@gmail.com")
{
Subject = "Email de Manuela Ibi Nutrição Integrada",
Body = $"{contato.Comentario}\nTelefone: {contato.Telefone}"
})
{
await smtpClient.SendMailAsync(message);
}
}
}
This class has to be instantiated in the controller with a line like "var whatever = new Email(???);" in order that the SendAsync method can be called.
But the big picture here is that I'm lost in this initialization. I just don't know what to call in "Email(something)".
Just, giving a little more information in case is needed:
The system should read the username, password from Secrets and thus I have the following line in Startup.cs:
services.Configure<ManuelaIbiEmail>(Configuration.GetSection("ManuelaIbiEmail"));
The ManuelaIbiEmail is a very simple POCO class:
public class ManuelaIbiEmail
{
public string Username { get; set; }
public string Password { get; set; }
}
The controller looks like:
public class ContactController : Controller
{
private readonly ManuelaIbiEmail manuelaIbiEmail;
public IActionResult Contact()
{
return View(new Contato());
}
[HttpPost]
public async Task<IActionResult> ContactAsync(Contato contato)
{
var email = new Email();
email.SendAsync(contato);
return Ok();
}
}
If anyone can be kind enough to tell me what I am missing, I'd appreciate.
Thank you in advance