In Asp.net, I can normally send emails using the following code:
using (var smtp = new SmtpClient())
{
await smtp.SendMailAsync(mailMessage);
}
With the smtp settings being provided in the web.config, which are then automatically used by the SmtpClient
. The web.config config section looks like:
<mailSettings>
<smtp deliveryMethod="Network">
<network host="myHost" port="25" userName="myUsername" password="myPassword" defaultCredentials="false" />
</smtp>
</mailSettings>
Is it possible to have config in the appSettings.json file in a dotnet core 2.0 application, which can then be used by the SmtpClient
, similar to Asp.net?
Application configuration in ASP.NET Core is performed using one or more configuration providers. Configuration providers read configuration data from key-value pairs using a variety of configuration sources: Settings files, such as appsettings. json.
The appsettings. json file is generally used to store the application configuration settings such as database connection strings, any application scope global variables, and much other information.
One of the simple and easy way to read the appsettings in Asp.net core is by using the IConfiguration using the namesapce Microsoft. Extensions. Configuration.
If you insist on using System.Net.Mail.SmtpClient, you can do it this way:
appsettings.json
{
"Smtp": {
"Server": "mail.whatever.com",
"Port": 25,
"FromAddress": "[email protected]"
},
}
Code:
public async Task SendEmailAsync(string email, string subject, string htmlMessage)
{
MailMessage message = new MailMessage();
message.Subject = subject;
message.Body = htmlMessage;
message.IsBodyHtml = true;
message.To.Add(email);
string host = _config.GetValue<string>("Smtp:Server", "defaultmailserver");
int port = _config.GetValue<int>("Smtp:Port", 25);
string fromAddress = _config.GetValue<string>("Smtp:FromAddress", "defaultfromaddress");
message.From = new MailAddress(fromAddress);
using (var smtpClient = new SmtpClient(host, port))
{
await smtpClient.SendMailAsync(message);
}
}
Where _config
is an implementation of IConfiguration
which is injected into the class in which the SendEmailAsync
method resides.
However, since it's obsolete, it might be better to explore other methods as mentioned in the comments above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With