user3473163
user3473163

Reputation: 11

How to add email configuration settings in web.config and retrieve the same from it?

I want to add the following smtp client configuration in web.config and use it in a c# code behind.

    var smtp = new SmtpClient
    {
        Host = "smtp.gmail.com",
        Port = 587,
        EnableSsl = true,
        DeliveryMethod = SmtpDeliveryMethod.Network,
        UseDefaultCredentials = false,
        Credentials = new NetworkCredential("feedback.****", "*****"),
    };

How to do it?

Upvotes: 0

Views: 1164

Answers (1)

Leo
Leo

Reputation: 14850

You have several options...

1- If using the .NET Framework SmtpClient class you can set up this information in the web.config file to use it as default settings so you don't have to specify them in code...

<system.net>
    <mailSettings>
      <smtp deliveryMethod="network" from="[email protected]">
        <network
          host="localhost"
          port="25"
          defaultCredentials="true"
        />
      </smtp>
    </mailSettings>
  </system.net>

more info in the MSDN Smpt documentation...

2- Or, you can set the settings as in the appSettings element and then retrieve the settings whenever you need to...

web.config

<appSettings>
    <add key="EmailHost" value="mail.domain.com"/>
    <add key="EmailPort" value="25"/>
  </appSettings>

Code

var smtp = new SmtpClient
    {
        Host = ConfigurationManager.AppSettings["EmailHost"],
        Port = int.Parse(ConfigurationManager.AppSettings["EmailPort"])
    };

Upvotes: 1

Related Questions