Monday, 20 May 2013

Sending an email by using C# Asp.Net


In this article I will explain how to send email using asp.net.

Sending e-mails with ASP.NET is very simple and straight forward. Microsoft .NET framework comes with an entire namespace for handling e-mails, - System.Net.Mail namespace. In the following examples, we will use two classes from this namespace: MailMessage class for the actual e-mail, and the SmtpClient class, for SMTP server.

C# .Net is very powerfull programming language. To send an email we require a SMTP server.
There are few companies who provides SMTP server for free of cost like gmail. Here we will use SMTP of the gmail as it is free of cost.

High level understanding -
for mailing through SMTP server of the gmail, we require :  
1. SMTP server name and port number(smtp.gmail.com and 587 for gmail). 
2. A valid gmail account of the sender along with username and password.
3. Recipient email address. 

Implementation -
Please follow below steps to send an email by using C# Asp.Net.

Step 1 : Create a class to implement a function to send an email.

namespace: using System.Net.Mail;

    /// <summary>
    /// Function for send an email
    /// </summary>
    /// <param name="from"></param>
    /// <param name="to"></param>
    /// <param name="cc"></param>
    /// <param name="bcc"></param>
    /// <param name="subject"></param>
    /// <param name="body"></param>
    /// <param name="IsHTML"></param>
    public static void SendMailMessage(string from, string to, string cc, string bcc, string subject, string body,bool IsHTML)
    {
        //Create an instance of mail message
        MailMessage tMailMessage = new MailMessage();
        //Assign sender email address
        tMailMessage.From = new MailAddress(from);
        //Assign recipient email address
        tMailMessage.To.Add(new MailAddress(to));
        //Check if cc is not null
        if(cc!=null && cc!="")
            tMailMessage.CC.Add(new MailAddress(cc));
        //Check if bcc is not null
        if (bcc != null && bcc != "")
            tMailMessage.Bcc.Add(new MailAddress(bcc));
        //Assign the subject 
        tMailMessage.Subject = subject;
        //Assign the mail body
        tMailMessage.Body = body;
        //assign the format of the mail body
        tMailMessage.IsBodyHtml = IsHTML;
        // Assign the priority of the mail message to normal
        tMailMessage.Priority = MailPriority.Normal;
        //Subject encoding by UTF-8
        tMailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
        //Body encoding by UTF-8
        tMailMessage.BodyEncoding = System.Text.Encoding.UTF8;

        //Create a new instance of SMTP client and pass name and port number         
       //of the smtp gmail server 
        SmtpClient tSmtpClient = new SmtpClient("smtp.gmail.com",587);
        //Enable SSL of the SMTP client
        tSmtpClient.EnableSsl = true;
        //Use delivery method as network
        tSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
        //Use DefaultCredentials set to false
        tSmtpClient.UseDefaultCredentials = false;
        //Pass account information of the sender
        tSmtpClient.Credentials = new System.Net.NetworkCredential("yourmail@gmail.com", "*********");
        tSmtpClient.Send(tMailMessage);
    }

Step 2 : Create an user interface to take email parameters.
<table>
    <tr>
    <td colspan="2">Send mail by using ASP.NET</td>
    </tr>
    <tr>
    <td>
    To
    </td>
    <td>
    <asp:TextBox ID="txtTo" runat="server"></asp:TextBox>
    </td>
    </tr>
    <tr>
    <td>
    CC
    </td>
    <td>
    <asp:TextBox ID="txtCC" runat="server"></asp:TextBox>
    </td>
    </tr>
    <tr>
    <td>
    BCC
    </td>
    <td>
    <asp:TextBox ID="txtBCC" runat="server"></asp:TextBox>
    </td>
    </tr>
    <tr>
    <td>
    Subject
    </td>
    <td>
    <asp:TextBox ID="txtSubject" runat="server"></asp:TextBox>
    </td>
    </tr>
        <tr>
    <td>
    Body
    </td>
    <td>
    <asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine"></asp:TextBox>
    </td>
    </tr>
    <tr>
    <td colspan="2">
    <asp:Button ID="btnSend" runat="server" Text="Send" onclick="btnSend_Click" />
    </td>
    </tr>
    </table>















Step 3 : Write code the event handler of the send button.
  • Create a region to declare global variable :
 #region Declaration
    private string _from = "";
    private string _to = "";
    private string _cc = "";
    private string _bcc = "";
    private string _subject = "";
    private string _body = "";
 #endregion


  • write code for the click event of send button
    /// <summary>
    /// Event handler: click event of the send button
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSend_Click(object sender, EventArgs e)
    {
        //assign values to the global variables from user interface/manually
        _from="vipulsachan.kiet@gmail.com";
        _to=txtTo.Text.Trim();
        _cc=txtCC.Text.Trim();
        _bcc=txtBCC.Text.Trim();
        _subject=txtSubject.Text.Trim();
        _body=txtBody.Text.Trim();
     
        //send mail
        EmailService.SendMailMessage(_from, _to, _cc, _bcc, _subject, _body, true);
    }


For video click here






4 comments:

  1. The name 'EmailService' does not exist in the current context

    ReplyDelete
    Replies
    1. Hi Nelson,

      Thanks for the comment, Here method SendMailMessage(...) is containing by the EmailService class, during implementation you can define the method SendMailMessage(..) in EmailService class. Then on button click you can call this method directly through the class name as it is static.

      Delete
    2. Thanks..
      successfully Run without error

      Delete