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)