justSteve
justSteve

Reputation: 5524

Storing a SMTP property in AppSetting

I'm working against Azure websites where the portal can be used to over-ride values in the web.config's AppSetting and ConnectionString sections. But other sections still require a transform or hard-coding of the web.config. I need to apply the same control over values found at /configuration/system.net/mailSettings/smtp

Ideally, I'd like to store a string in an AppSetting value and then, when the site boots, it parses this string and over-writes the initial contents of my SMTP section with parsed values found in AppSettings.

Big picture objective: eliminate reliance on hard-coded smtp values of the web.config and instead, apply those values from the portal's listing of AppSettings. Possible?

thx

Upvotes: 1

Views: 262

Answers (1)

ahmelsayed
ahmelsayed

Reputation: 7392

I'm not too familiar with System.Net.Mail, but you can always read and initialize your own config. You can set the following AppSettings in the portal

smtp.host = <hostName>
smtp.port = <port>
smtp.userName = <userName>
smtp.password = <password>
smtp.defaultCredentials = <true | false>

and then have something like that in your code.

public SmtpClient GetSmtpClient()
{
    Func<string, string> config = s => ConfigurationManager.AppSettings[s] ?? System.Environment.GetEnvironmentVariable(s);
    return new SmtpClient
    {
        Host = config("smtp.host"),
        Port = int.Parse(config("smtp.port")), // handle parsing errors
        Credentials = new NetworkCredential(config("smtp.userName"), config("smtp.userName")),
        UseDefaultCredentials = bool.Parse(config("smtp.defaultCredentials")), //handle parsing errors
    };
}

then when debugging locally you can rely on Environment Variables and when deploying to Azure you use the AppSettings.

Upvotes: 1

Related Questions