Friday, August 26, 2016

Sending Email in ASP.NET

For sending email in ASP.NET , we have to use namespace, System.Net.Mail
which contains its main classes, MailMessage and SmtpClient.

As mail is sent to an SMTP (Simple Mail Transfer Protocol) Server which
forwards to the recipient server, we require an accessible SMTP Server.

Suppose I am sending email on a Button's Click in a web form,
code for this is as following :

C# Code (.aspx.cs) :


using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;

public partial class TestEmail : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            MailMessage mailMessage = new MailMessage();
            mailMessage.To.Add("To Address");
            mailMessage.From = new MailAddress("From Address");
            mailMessage.Subject = "Test e-mail from the website";
            mailMessage.Body = "Hi, this is a test e-mail!";
            SmtpClient smtpClient = new SmtpClient("smtp.domain.com");
            smtpClient.Send(mailMessage);
            lblMessage.Text="E-mail sent!";
        }
        catch (Exception ex)
        {
            lblMessage.Text = "E-mail sending failed - error : " + ex.Message;
        }

    }
}

We can set various properties of the MailMessage class.
Suppose we want to send as an HTML format with HTML
tags and styles, we can concatenate strings and pass to the Body
and set IsBodyHtml to true.

If we want to set the priority, we can use Priority property.
For eg. if we want to send a high priority email, add the following code  :

mailMessage.Priority = MailPriority.High;

If we want to send attachment, we can create instance of Attachment class
inside System.Net.Mail and implement as :

Attachment attach = new Attachment(Server.MapPath(strFileName));
mailMessage.Attachments.Add(attach);

Normally we can send mail without providing credentials but some SMTP servers
require credentials for authenticating.

We can set SMTP details in web.config file as :

<configuration>
  <system.net>
    <mailSettings>
      <smtp>
        <network 
             host="Host Name" 
             port="Port Number"
             userName="username"
             password="password" />
      </smtp>
    </mailSettings>
  </system.net>
  <system.web>
    ...
  </system.web>
</configuration>

In  this case of using web.config, no need to specify SmtpClient Details
in code. It will take automatically from web.config.

Server side implementation code is as following :

  SmtpClient smtpClient = new SmtpClient();
  smtpClient.Send(mailMessage);

No comments:

Post a Comment