Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SMTP settings in appSettings.json in dotnet core 2.0

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?

like image 626
ViqMontana Avatar asked Feb 21 '19 09:02

ViqMontana


People also ask

Can I use app config in .NET Core?

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.

What is the use of Appsettings json in .NET Core?

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.

Where is application settings in .NET Core?

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.


1 Answers

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.

like image 151
HaukurHaf Avatar answered Sep 19 '22 12:09

HaukurHaf