Tuesday, August 16, 2011

How to send email in asp.net?

This is a frequently asked questions in different forum and community sites. So I have decided to show here a simple way of sending HTML email using System.Net.Mail.

Prior to .Net framework 2.0 System.Web.Mail were used for this purpose. From .Net framework 2.0 System.Net.Mail was introduced and recommended for sending mail and System.Web.Mail is absolute now. Because within System.Net.Mail namespace .net framework introduces much richer Email API support.

There are 16 mail related classes defined in System.Net.Mail namespace. Two core main classes are:
MailMessage and SmtpClient.
MailMessage - represents an email message that have properties like From, To, Subject, Body etc.
SmtpClient - sends message to specified SMTP server. 

Before sending email you need to set SMTP configuration to your web.config file. Here is an example of how to configure it:

<system.net>
    <mailSettings>
      <smtp>
        <network host="smtpserver" port="25" userName="username" password="pass"  defaultCredentials="true"  />
      </smtp>
    </mailSettings>
  </system.net>

 Following code snippet shows codes for sending mail:




using System;
using System.Net.Mail;
using System.Text;
 
public partial class Mailer : System.Web.UI.Page
{
 
    private MailMessage BuildMail()
    {
        string from, to, bcc, cc, subject, body;
        from = "from@foo.com";   //Email Address of Sender
        to = "to@foo.com";   //Email Address of Receiver
        bcc = "bcc@foo.com";
        cc = "cc@foo.com";
        subject = "This is a test email.";
 
        StringBuilder sb = new StringBuilder();
        sb.Append("Hi Scott,<br/>");
        sb.Append("This is a test email. We are testing out email client. Please don't mind.<br/>");
        sb.Append("We are sorry for this unexpected mail to your mail box.<br/>");
        sb.Append("<br/>");
        sb.Append("Thanking you<br/>");
        sb.Append("Tips.Asp.Net");
        
        body =sb.ToString() ;
 
        MailMessage mail = new MailMessage();
        mail.From = new MailAddress(from);
        mail.To.Add(new MailAddress(to));
 
        if (!string.IsNullOrEmpty(bcc))
        {
            mail.Bcc.Add(new MailAddress(bcc));
        }
        if (!string.IsNullOrEmpty(cc))
        {
            mail.CC.Add(new MailAddress(cc));
        }
 
        mail.Subject = subject;
        mail.Body = body;
        mail.IsBodyHtml = true;
 
        return mail;
    }
 
    private void SendEMail(MailMessage mail)
    {
        SmtpClient client = new SmtpClient();
        client.Send(mail);
    }

    protected void btnSend_Click(object sender, EventArgs e)
    {
        MailMessage mail = BuildMail();
        SendEMail(mail);
    }
}



 Yahoo and HotMail does not support SMTP.


Hope this will help.


Thanks




 

No comments:

Post a Comment