I'm trying to build a web-app in ASP.NET core 3.1 for managing a company's clients. When the user saves a new client in the database, I want the app to send a welcome mail to the client.
I tried doing that with the SmtpClient class but microsoft itself seems to discourage that:
Important. We don't recommend that you use the SmtpClient class for new development because SmtpClient doesn't support many modern protocols. Use MailKit or other libraries instead.
So I decided to use the MailKit library and I've coded this so far:
// Send a welcome email.
MimeMessage message = new MimeMessage();
message.From.Add(new MailboxAddress("CompanyName", "email"));
message.To.Add(MailboxAddress.Parse(obj.Email));
message.Subject = "Welcome mail";
message.Body = new TextPart("plain")
{
Text = @"Welcome " obj.Name "!"
};
SmtpClient client = new SmtpClient();
client.Connect("smtp.gmail.com", 465, true);
client.Authenticate("mail", "password");
client.Send(message);
client.Disconnect(true);
client.Dispose();
Note that the above segment of code is written in the controller that handles the storing the new client. Right after the validation and saving the db changes, I send the email.
This works fine, but I want to see if it's possible to read all things like the mail address, its password, the smtp client, the port etc, from a config file in the app folder, instead of them being hard-coded. I think that MailKit can't read the web.config file, is there anything else I can do? Any help would be appreciated!
CodePudding user response:
Yes you can!
In you Startup.cs :
services.Configure<EmailSettings>(Configuration.GetSection("EmailSection"));
Create the configuration class EmailSettings :
public class EmailSettings
{
public string Smtp { get; set; }
public string SendFrom { get; set; }
public string Password { get; set; }
public int Port { get; set; }
}
Then add this on you appsettings.json :
...
"EmailSection": {
"Smtp": "smtp.gmail.com",
"SendFrom": "[email protected]",
"Password": "123456789",
"Port": 465
},
...
Finally, you can use dependency injection for call you configuration class EmailSettings from a controller or whatever you want :
public class HomeController : Controller
{
private EmailSettings _emailSettings;
// Constructor of controller
public HomeController : Controller (IOptions<EmailSettings> emailSettings)
{
_emailSettings = emailSettings;
}
public IActionResult Index()
{
string getSmtp = _emailSettings.Smtp;
string getPassword = _emailSettings.Password;
// ...
}
}
