Email Sending in ASP.net 2.0

We will have requirements to send email from our asp.net applications. This article will help us understand some of the available techniques we can use to send email from asp.net applications. With the introduction of .Netframework 2.0, the classes for sending email are packed in System.Net.Mail namespace as opposed to System.Web.Mail namespace in 1.x framework.

 

This article will focus on following concept Simplest way of sending email Writing HTML Email Creating Email with attachment.

Import the namespace, and create instances of required classes

We are going to use the SmtpMail and MailMessage classes, which belong to the System.Web.Mail namespace. In order to use them, we will need to import the System.Web.Mail namespace like this:

<%@ Import Namespace="System.Web.Mail" %>

Exploring the Classes in the System.Net.Mail Namespace
There are 16 different classes in the System.Net.Mail namespace, all related to send email to a specified Simple Mail Transfer Protocol (SMTP) server for delivery. The two core classes in this namespace are:

  • MailMessage - represents an email message; has properties like From, To, Subject, Body, and so on.
  • SmtpClient - sends a specified MailMessage instance to a specified SMTP server.

When sending an email from an ASP.NET 2.0 page you will, typically:

  1. Create a MailMessage object
  2. Assign its properties
  3. Create an instance of the SmtpClient class
  4. Specify details about the SMTP server to use (if they're not already specified within Web.config)
  5. Send the MailMessage via the SmtpClient object's Send method

Steps 1 and 2 may be bypassed as the SmtpClient class's Send method can accept either a MailMessage object or four strings, representing the from, to, subject, and body contents of the email message.

The System.Net.Mail namespace's other classes allow for more advanced email functionality. There are classes that can be used to add attachments to an email message, to embed objects within an email, to specify SMTP server authentication information, and Exception-derived classes for handling SMTP-specific exceptions.

One of the most common functionalities used in Web development is sending email from a Web page.

Using the code

The HTML Design contains provision to enter senders name, email id and his comments. On click of the send email button the details will be sent to the specified email .

The Send mail functionality is similar to Dotnet 1.1 except for few changes

  1. System.Net.Mail.SmtpClient is used instead of System.Web.Mail.SmtpMail (obsolete in Dotnet 2.0).
  2. System.Net.MailMessage Class is used instead of System.Web.Mail.MailMessage (obsolete in Dotnet 2.0)
  3. The System.Net.MailMessage class collects From address as MailAddress object.
  4. The System.Net.MailMessage class collects To, CC, Bcc addresses as MailAddressCollection.
  5. MailMessage Body Format is replaced by IsBodyHtml

.ASPX CODE:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="sendmail.aspx.cs" Inherits="sapnamalik_sendmail" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

        <div>

            <table id="tblemail" runat="server" cellpadding="0" cellspacing="0" width="100%">

                <tr>

                    <td>

                        <fieldset>

                            <legend style="border: none; font-weight: bold; color: #660099; font-size: 12pt;

                                font-family: Segoe UI">Send Your Email&nbsp;</legend>

                            <table id="tblbody" runat="server" cellpadding="2" cellspacing="2" width="100%">

                                <tr>

                                    <td colspan="2" align="center">

                                        Fields marked with an asterisk (<asp:Label ID="Label1" runat="server" CssClass="redtext"

                                            Text="*"></asp:Label>)are mandatory

                                    </td>

                                </tr>

                                <tr>

                                    <td colspan="2" align="center">

                                        <asp:Label ID="lblmail" CssClass="redtext" runat="server"></asp:Label></td>

                                </tr>

                                <tr>

                                    <td width="10%" align="right">

                                        <asp:Label ID="lblto" runat="server" Text="To:"></asp:Label>

                                        <asp:Label ID="lblredstar1" runat="server" CssClass="redtext" Text="*"></asp:Label>

                                    </td>

                                    <td align="left" width="90%">

                                        <asp:TextBox ID="txtemailto" Width="50%" runat="server" TabIndex="1"></asp:TextBox>

                                        <asp:RegularExpressionValidator ID="REVUserEMail" runat="server" CssClass="redtext"

                                            Display="static" ControlToValidate="txtemailto" ErrorMessage="Enter valid Email Address"

                                            ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>

                                    </td>

                                </tr>

                                <tr>

                                    <td width="10%" align="right">

                                        <asp:Label ID="lblcc" runat="server" Text="CC:"></asp:Label>

                                    </td>

                                    <td align="left" width="90%">

                                        <asp:TextBox ID="txtemailcc" Width="50%" runat="server" TabIndex="10"></asp:TextBox>

                                    </td>

                                </tr>

                                <tr>

                                    <td width="10%" align="right">

                                        <asp:Label ID="lblBcc" runat="server" Text="BCC:"></asp:Label>

                                    </td>

                                    <td align="left" width="90%">

                                        <asp:TextBox ID="txtemailbcc" Width="50%" runat="server" TabIndex="10"></asp:TextBox>

                                    </td>

                                </tr>

                                <tr>

                                    <td width="10%" align="right">

                                        <asp:Label ID="lblfrom" runat="server" Text="From:"></asp:Label>

                                        <asp:Label ID="lblredstar3" runat="server" CssClass="redtext" Text="*"></asp:Label>

                                    </td>

                                    <td align="left" width="90%">

                                        <asp:TextBox ID="txtemailfrom" Width="50%" runat="server"></asp:TextBox>

                                        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" CssClass="redtext"

                                            Display="static" ControlToValidate="txtemailfrom" ErrorMessage="Enter valid Email Address"

                                            ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>

                                    </td>

                                </tr>

                                <tr>

                                    <td width="10%" align="right">

                                        <asp:Label ID="lblsubject" runat="server" Text="Subject:"></asp:Label>

                                        <asp:Label ID="lblredstar4" runat="server" CssClass="redtext" Text="*"></asp:Label>

                                    </td>

                                    <td align="left" width="90%">

                                        <asp:TextBox ID="txtsubject" Width="50%" runat="server"></asp:TextBox>

                                    </td>

                                </tr>

                                <tr>

                                    <td width="10%" align="right">

                                        <asp:Label ID="lblAttachFile" runat="server" Text="File to send:"></asp:Label>

                                    </td>

                                    <td align="left" width="90%">

                                        <input type="file" id="fileAttachement" runat="server" name="fileAttachement" />

                                    </td>

                                </tr>

                                <tr>

                                    <td>

                                    </td>

                                    <td align="left">

                                        <asp:Button ID="btnSendEmail" runat="server" Width="60px" Text="Send Mail" OnClick="btnSendEmail_Click" />&nbsp;

                                    </td>

                                </tr>

                            </table>

                        </fieldset>

                    </td>

                </tr>

            </table>

        </div>

    </form>

</body>

</html>

 

.CS CODE:-

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Net.Mail;

using System.Data.SqlClient;

using System.IO;

 

public partial class sapnamalik_sendmail : System.Web.UI.Page

{

    SqlDataAdapter da;

    DataSet ds = new DataSet();

    SqlCommand cmd = new SqlCommand();

    SqlConnection con;

    string FileName;

    protected void Page_Load(object sender, EventArgs e)

    {

    }

    protected void btnSendEmail_Click(object sender, EventArgs e)

    {

        if (txtemailto.Text == "" || txtemailfrom.Text == "" || txtemailcc.Text == "" || txtemailbcc.Text == "" || txtsubject.Text == "")

        {

            txtemailto.Focus();

            lblmail.Text = "Please fill all mandatory fields.";

            lblmail.Visible = true;

            return;

        }

        sendMessage();

        txtemailto.Text = "";

        txtemailfrom.Text = "";

        txtemailcc.Text = "";

        txtemailbcc.Text = "";

        txtsubject.Text = "";

    }

    private void sendMessage()

    {

        string cc = txtemailcc.Text;

        string bcc = txtemailbcc.Text;

        SmtpClient smtpClient = new SmtpClient();

        MailMessage mailMessage = new MailMessage();

        try

        {

            MailAddress fromAddress = new MailAddress(txtemailfrom.Text);

            mailMessage.From = fromAddress;

            string MailTo = txtemailto.Text;

            mailMessage.To.Add(MailTo);

 

            //Sending Email with CC and BCC options

            //Set the CC address of the mail message

            if (txtemailcc.Text.Trim().Length != 0)

                mailMessage.CC.Add(txtemailcc.Text);

            //Set the BCC address of the mail message

            if (txtemailbcc.Text.Trim().Length != 0)

                mailMessage.Bcc.Add(txtemailbcc.Text);

 

            mailMessage.Subject = txtsubject.Text;

 

            //Sending Email with Attachment facility

            if (fileAttachement.PostedFile != null)

            {

                HttpPostedFile AttachFile = fileAttachement.PostedFile;

                int AttachFileLength = AttachFile.ContentLength;

                if (AttachFileLength > 0)

                {

                    FileName = Path.GetFileName(fileAttachement.PostedFile.FileName);

                }

            }

            //Note: When you make "IsBodyHtml" to true make

            //ValidateRequest="false" in page derective

            //As to make HTML content passed.          

            string Body = "";

            Body += '\n' + "Email:" + txtemailfrom.Text;

            Body += '\n' + "";

            mailMessage.IsBodyHtml = true;

            mailMessage.Body = Body;

            //Sending Email with Reply-To options

            //Setting Reply address.

            if (txtemailto.Text.Trim().Length != 0)

            {

                mailMessage.Headers.Add("Reply-To", txtemailto.Text);

            }

            else

            {

                mailMessage.Headers.Add("Reply-To", txtemailto.Text);

            }

            smtpClient.Host = "localHost";

            smtpClient.Send(mailMessage);

            lblmail.Visible = true;

            lblmail.Text = "Your mail has been sent successfully";

            tblemail.Visible = true;

        }

        catch (Exception ex)

        {

            lblmail.Visible = true;

            lblmail.Text = "There has been some error, please try again after some time.";

        }

    }

}

 

Output:


mailsending.bmp

Up Next
    Ebook Download
    View all
    Learn
    View all