Home DotNet Sending Email with ASP.NET
Sending Email with ASP.NET

Whether you are building a personal website or a business website, there will be times when you will need to send emails with asp.net within your web application. Email can be sent to an individual, a website or a group of people. Using the server side code this can be easily achieve. 

During the era of ASP (Active Server Pages) sending email from the web application can be quiet a challenging task. However since the arrival of ASP.NET send email was an easy task. 

To send email out in .NET Framework version 1.x the namespace System.Web.Mail must be use to send out email. The System.Web.Mail contains several handy classes to assist programmer to quickly send email with a few scant lines of code. Moving to .NET 2.x there is a new namespace System.Net.Mail which consist of 16 different classes assist programmer to write code to deliver emails. Out of the 16 different classes there are 2 core classes that helps programmer to quickly write code to send email. 

  • MailMessage – A class that contain mail message, and has properties such as From, To, Subject, Body and etc.
  • SmtpClient – A class that specify which SMTP server is use to send emails.

This article will be primarily focusing on sending email with System.Net.Mail as this is the prefer method of send email over the deprecated System.Web.Mail. 

To send an email these it generally involves five steps: 

  • Create a new mail message
  • Set the property for the new mail message (eg. mail from, mail to, mail subject and mail body)
  • Create a new SmtpClient instance
  • Set the properties of the SmtpClient either in code or via the web.config file.
  • Send out email using the send method provided from the SmtpClient object.

 The first step is to configure the SMTP setting in the web.config file. If you server allow anonymous login then you can omit the username and password.

<configuration>

  <system.web>

 

  </system.web>

 

  <!-- Apply the smtp setting -->   

  <system.net>

    <mailSettings>

      <smtp>

        <network

             host="TheRelayServerHostName"

             port="portNumber"

             userName="username"

             password="password" />

      </smtp>

    </mailSettings>

  </system.net>

</configuration>

 

Properties of the SMTP setting:

Host: This is the name of the relay server, for example it could be smtp.yahoo.com. Port: the default port is 25, if the server uses a different port number then specifies the port number.Username and password: if the server setting does not allow anonymous connection then enter in the username and password to the SMTP server.

For illustration purposes I have created a sample enquiry form which the website user can submit their enquiry and the form will send an email to the site administrator.

Here is an example of the HTML form that the user can submit an enquiry to the site administrator.

When the user click on the Submit button it will trigger the server side code and an email is sent to the site administrator.

send-email-with-asp-net

EmailDemo.aspx 

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

 

<!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>Email Demo</title>

</head>

<body>

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

    <div>

        <h2>Enquiry Form</h2>   

    </div>

    <div>

        <table>

            <tr>

                <td><b>Name:</b></td>

                <td><asp:TextBox ID="txtName" runat="server" Width="280px"></asp:TextBox></td>

            </tr>

            <tr>

                <td><b>Email:</b></td>

                <td><asp:TextBox ID="TextBox1" runat="server" Width="280px"></asp:TextBox></td>

            </tr>

            <tr>

                <td><b>Subject:</b></td>

                <td><asp:TextBox ID="TextBox3" runat="server" Width="280px"></asp:TextBox></td>

            </tr>

            <tr>

                <td><b>Enquiry Detail:</b></td>

                <td><asp:TextBox ID="TextBox2" runat="server" Height="149px" TextMode="MultiLine"

                        Width="408px"></asp:TextBox></td>

            </tr>

            <tr>

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

                    <asp:Button ID="btnSubmit" runat="server" Text="Submit Enquiry"

                        onclick="btnSubmit_Click" />

                </td>

            </tr>

        </table>

    </div>

    </form>

</body>

</html>

 

EmailDemo.cs

using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

using System.Net.Mail;

 

public partial class EmailDemo : System.Web.UI.Pagea

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

    protected void btnSubmit_Click(object sender, EventArgs e)

    {

        string ToAddress = " This e-mail address is being protected from spambots. You need JavaScript enabled to view it ";

 

        //Create a new mail message instance

        MailMessage mailMsg = new MailMessage(txtEmail.Text, ToAddress);

 

        //Set the require property

        mailMsg.Subject = txtSubject.Text;

        mailMsg.Body = "Name: " + txtName.Text + Environment.NewLine + txtEnquiry.Text;

        mailMsg.IsBodyHtml = false;

 

        //Create the new SmtpClient instance

        SmtpClient smtp = new SmtpClient();

 

        //Send the Mail Message to the specify smtp server.

        smtp.Send(mailMsg);

    }

} 



Comments (8)
  • fdsfdsf
    This is brilliant, thanks.
  • oil mill

    This is a brilliant post, im really glad I found it thank you
  • coach canada  - information
    It's really a very good article,I learn so much thing from it,thanks.
  • Naresh  - how to send email with schedule time
    hi,
    your artical is very good learn new things.
    please send the code for me ,how to send email
    with a scheduled time and date to all or specific users.All users email id's are stored in the database.

    please help me.

    thanks in advance.
  • admin
    Naresh - if you want to send email with a schedule time, then I suggest you use Windows services as it can provide a timer which you can schedule when to send out email.
  • Joe  - What if
    What if there was a problem sending the message. Could you redirect to a page with a info? I've looked for somthing like this but no luck.
  • admin
    Joe - you could trap an error with an exception. If there is an error then redirect the page. Also you could check out this one SendAsync(MailMessage, Object).
  • Ebel  - Great article
    There are few people would know a solution like this.
Write comment
Your Contact Details:
Comment:
[b] [i] [u] [url] [quote] [code] [img]   
:D:angry::angry-red::evil::idea::love::x:no-comments::ooo::pirate::?::(
:sleep::););)):0
Security
Please input the anti-spam code that you can read in the image.

"