M Armaan
M Armaan

Reputation: 39

Get Mail Setting from Web.Config in SendAsync Method?

I am working on Forgot Password Functionality. In my web.config file I have done the mail settings:

<system.net>
    <mailSettings>
      <smtp from="email">
        <network host="host" port="25" userName="" password="=" enableSsl="true" />
      </smtp>
    </mailSettings>
</system.net>

In my SendAsync method I am trying to read setting from web.config:

SmtpClient client = new SmtpClient();
return client.SendMailAsync(ConfigurationManager.AppSettings["SupportEmailAddr"],
                                    message.Destination,
                                    message.Subject,
                                    message.Body);

I have no idea what is this: AppSettings["SupportEmailAddr"]

I took this from here.

It is giving me following exception:

Value cannot be null. Parameter name: from

Upvotes: 0

Views: 1016

Answers (1)

Ashley Medway
Ashley Medway

Reputation: 7301

In your web.config file you have a section called: <appSettings>.

That is what ConfigurationManager.AppSettings is referring too.

["SupportEmailAddr"] is looking at a specific setting called SupportEmailAddr.

In your web.config it would look something like this:

<appSettings>
    <add key="SupportEmailAddr" value="[email protected]" />
</appSettings>

You are getting the value cannot be null message because you will not have the setting in your web.config as above.

So to fix the error message find your <appSettings> and add:

<add key="SupportEmailAddr" value="[email protected]" />

Alternatively, if you have the current value in your AppSettings already then just change the key that you are looking for in the C# code.

ConfigurationManager.AppSettings["CorrectAppSettingKey"]

Note: if you plan on using any of the web.config inheritance features you should WebConfiguratonManger.AppSettings instead of ConfigurationManager.AppSettings. See the difference between the two here: What's the difference between the WebConfigurationManager and the ConfigurationManager?

Upvotes: 1

Related Questions