Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Reading SMTP settings from web.config

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 362
    Comment on it

    In .Net applications, we have a standard way of specifying the SMTP setting in configuration file called web.config in web apps and app.config in other apps. We can define the settings needed for SMTP setup in these configuration files and then read them in our code when we need to send email.

    Here is the sample configuration section for SMTP settings.

    <configuration> 
    	<system.net>
    	  <mailSettings>
    	    <smtp deliveryMethod="network" from="xyz@gmail.com">
    	      <network 
                host="smtp.gmail.com"
    	        port="587"
    	        enableSsl="true"
    	        userName="xyz@gmail.com"
    	        password="password"
    	    />
    	    </smtp>
    	  </mailSettings>
    	</system.net> 
    </configuration>

     

    The system.net section is written under configuration section of config file. Then we have mailsettings section and inside mail setting section, we define SMTP settings.

    We cannot directly read these SMTP settings in our application. To read these setting we need to read the section in code. Here is the sample code.

    SmtpSection section = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp"); 
    	string from = section.From;
    	string host = section.Network.Host;
    	int port = section.Network.Port;
    	bool enableSsl = section.Network.EnableSsl;
    	string user = section.Network.UserName;
    	string password = section.Network.Password;

    As you can see in the above code sample, we are first reading the smtp section using ConfigurationManager.GetSection("system.net/mailSettings/smtp") and later with the help of this section object, we are reading the settings needed for sending email.

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: