How to send email in ASP.NET?

string fromName = ConfigurationManager.AppSettings["defaultEmailFromName"];

string fromEmail = ConfigurationManager.AppSettings["defaultEmailFrom"];

System.Net.Mail.MailMessage email = new System.Net.Mail.MailMessage();

email.IsBodyHtml = true;

email.From = new System.Net.Mail.MailAddress(fromEmail, fromName);

email.To.Add(new System.Net.Mail.MailAddress("some@web.com", "Sender Name"));

email.Subject = "Email Subject";

 

using (StreamReader sr = File.OpenText("HTMLTemplates/Template.htm"))

{

  body = sr.ReadToEnd();

  sr.Close();

}

 

body = body.Replace("[Name]", "Customer Name");

email.Body = body;

 

try

{

   System.Net.Mail.SmtpClient emailProvider = new System.Net.Mail.SmtpClient();

   emailProvider.Send(email);

}

 

catch (Exception anException)

{

   // Exception handaling

}

 

web.config

 

<system.net>

  <mailSettings>

    <smtp>

        <network host="localhost" port="25" defaultCredentials="true"/>

    </smtp>

  </mailSettings>

</system.net>

 

Don't forget to set IIS Default smpt relay settings restrictions to grant access for 127.0.0.1.


Posted on Monday, March 17, 2008 by | Comments (2) | Add Comment

Comments

Gravatar

Re:How to send email in ASP.NET?

Could you send me some more....

Posted on 10/20/2010 2:09:01 AM by Rajesh chettri #
Gravatar

Re:How to send email in ASP.NET?

I love you for all your great posts

Posted on 6/30/2011 7:35:45 AM by aa #

New Comment

Your Name:
Email (for internal use only):
Comment:
 
Code above:

Categories

Recent Tweets

  • Simon Ince's Blog: Hierarchies with HierarchyID in SQL 2008 http://t.co/xSDwiF6rRS.
  • Visual Studio 2010 WAS painfully slow - CodeProject http://t.co/Usba1x6CZy

Valid HTML5