Tuesday, August 18, 2009 10:02 PM
In the old days, we have to manually create custom configuration sections if we want to do cool stuff with app/web.config or simply just put the values in the appSettings section. However, there are a few config options that are out there that most developers don’t know about, a perfect example is the mailSettings config section which allows you to setup your mail settings in your configuration file and simply call the SMTPClient to send an email and by doing so, changing settings can be done on the fly and oh’ if you are worried about security, don’t forget you can definitely encrypt your configuration file if you need to.
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="name@domain.com">
<network host="smtp.mail.com"
userName="name@domain.com"
password="blog.dotnetclr.com" port="25"/>
</smtp>
</mailSettings>
</system.net>
And here is the sample C# code that will use the above configuration settings
public void SendBy(string to, string subject, string body)
{
var mailMessage = new System.Net.Mail.MailMessage();
mailMessage.To.Add(to);
mailMessage.Subject = subject;
mailMessage.Body = body;
var smtpClient = new SmtpClient();
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
}