Sunday, May 31, 2009

Configuring SMTP using WebConfig

Scenario:
Sending mail is one of the most common requirements for any Web Application. Usually SMTP server name change for different environments and there is a need for easily changing the value of SMTP server.

Solution:
Its possible to use a have SMTP server name as AppSetting but then you need to read it in Code and assign it to Smtp Client object.

Here's a shortcut.

Code:

string body = "This mail is from SMTP configured in Web.Config" ;

MailMessage message = new MailMessage("admin@server.com","EnterToEmailAddress", "Item Updated", body);

SmtpClient client = new SmtpClient();

client.Send(message);
WebConfig:
<configuration>
<system.net>
<mailSettings>
<smtp from="myemail@email.com">
<network host="smtp.company.com" port="25" />
</smtp>
</mailSettings>
</system.net>
</configuration>

0 comments: