Sending An E-Mail Using ASP.NET With C#

Introduction

Sending email is a very common task in any web application for many purposes. We can send OTP as an email to email addresses to confirm users' accounts in case of login functionality in the ASP.NET project. Therefore in this article, I will be explaining how an email can be sent using ASP.NET with C#. I will be working on window forms of the ASP.NET web application. I will be demonstrating how to use asp.net to build a web application to send an email.

In order to send electronic mail using ASP.NET, the .NET developer platform provides the System.Net.Mail Namespace.

The System.Net.Mailnamespace contains classes used to send electronic mail to a Simple Mail Transfer Protocol (SMTP) server for delivery. I will be using SmtpClient and MailMessage to demonstrate how we can create web applications to send email by using the Simple Mail Transfer Protocol (SMTP).

SmtpClient Class

The SmtpClient Class belongs to the System.Net.Mail namespace. The SmtpClient class allows applications to send email by using the Simple Mail Transfer Protocol (SMTP).

The SmtpClient class is used to send email to an SMTP server for delivery. To construct and send an email message by using SmtpClient, you must specify the following information

  • The SMTP host server and port that can be used to send email.
  • Credentials property for authentication, if required by the SMTP server.
  • The email address of the sender.
  • The email address or addresses of the recipients.
  • The message content.

The SmtpClient class constructors along with their overloads are as follows.

SmtpClient()
Initializes a new instance of the SmtpClient class by using configuration file settings.
SmtpClient(String)
Initializes a new instance of the SmtpClient class that sends email by using the specified SMTP server.
SmtpClient(String, Int32)
Initializes a new instance of the SmtpClient class that sends email by using the specified SMTP server and port.

Some of the widely used properties of the SmtpClient class are as follows.

Credentials
Gets or sets the credentials used to authenticate the sender.
DeliveryMethod
Specifies how outgoing email messages will be handled.
EnableSsl
Specify whether the SmtpClient uses Secure Sockets Layer (SSL) to encrypt the connection.
Host
Gets or sets the name or IP address of the host used for SMTP transactions.
Port
Gets or sets the port used for SMTP transactions.
UseDefaultCredentials
Gets or sets a Boolean value that controls whether the DefaultCredentials are sent with requests.

Some of the widely used methods of the SmtpClient class are as follows.

Send(MailMessage)
Sends the specified message to an SMTP server for delivery.
Send(String, String, String, String)
Sends the specified email message to an SMTP server for delivery. The message sender, recipients, subject, and message body are specified using String objects.


MailMessage Class

MailMessage Class represents an email message that can be sent using the SmtpClient class. Instances of the MailMessage class are used to construct email messages that are transmitted to an SMTP server for delivery using the SmtpClient class.

The sender, recipient, subject, and body of an email message may be specified as parameters when a MailMessage is used to initialize a MailMessage object. These parameters may also be set or accessed using properties on the MailMessage object.

Following are the properties of the MailMessage class.

To
Gets the address collection that contains the recipients of this email message.
From
Gets or sets from the address for this email message.
Subject
Gets or sets the subject line for this email message.
Body
Gets or sets the message body.

The MailMessage class constructors along with their overloads are as follows,

MailMessage()
Initializes an empty instance of the MailMessage class.
MailMessage(MailAddress, MailAddress)

Initializes a new instance of the MailMessage class by using the specified MailAddress class objects.

MailMessage(String, String)

Initializes a new instance of the MailMessage class by using the specified String class objects.

MailMessage(String, String, String, String)
Initializes a new instance of the MailMessage class.


Attachment Class

Represents an attachment to an email.

The Attachment class is used with the MailMessage class. All messages include a Body, which contains the content of the message. In addition to the body, you might want to send additional files. These are sent as attachments and are represented as Attachment instances. To add an attachment to a mail message, add it to the MailMessage.Attachments collection.

Attachment content can be a String, Stream, or file name. You can specify the content in an attachment by using any of the Attachment constructors.

The Attachment class constructors along with their overloads are as follows.

Attachment(Stream, ContentType)
Initializes a new instance of the Attachment class with the specified stream and content type.
Attachment(Stream, String)
Initializes a new instance of the Attachment class with the specified stream and name.
Attachment(Stream, String, String)
Initializes a new instance of the Attachment class with the specified stream, name, and MIME type information.
Attachment(String)
Initializes a new instance of the Attachment class with the specified content string.
Attachment(String, ContentType)
Initializes a new instance of the Attachment class with the specified content string and ContentType.

Some of the widely used properties of the Attachment class are as follows.

ContentId
Gets or sets the MIME content ID for this attachment.
ContentStream
Gets the content stream of this attachment.
ContentType
Gets the content type of this attachment.
Name
Gets or sets the MIME content type name value in the content type associated with this attachment.
ContentDisposition
Gets the MIME content disposition for this attachment.

Some of the widely used methods of Attachment class are as follows.

CreateAttachmentFromString(String, ContentType)
Creates a mail attachment using the content from the specified string, and the specified ContentType.
CreateAttachmentFromString(String, String)

Creates a mail attachment using the content from the specified string, and the specified MIME content type name.

CreateAttachmentFromString(String, String, Encoding, String)
Creates a mail attachment using the content from the specified string, the specified MIME content type name, character encoding, and MIME header information for the attachment.

The following web applications demonstrate sending an email message to an SMTP server for delivery and attaching a file to an email message.

Creating ASP.NET web application

In order to create an asp.net web application, open Visual Studio 2017. Go to the menu on the top, click on File, then click on New, then click on Project.

Sending an E-Mail Using ASP.NET With C#

A new Project dialogue will open, select ASP.NET Web Application. Specify the name of the project and click on the OK button.

A new dialogue will open, select an empty template, and click on ok.

Sending an E-Mail Using ASP.NET With C#

Now we will create a simple web form that allows users to specify to address, from address, subject, message, and a send button to send the message to the provided email address that is sending email on the web.

To create a web form, right-click on the project, then click on Add, and click on New Item.

A dialogue box named Add New Item will open, click on the web option on the left side of the dialogue box. Select Web Form from the given options, specify the name of the form, and click on the Add button.

Sending an E-Mail Using ASP.NET With C#

Inside index.aspx web form which runs on the server, we will add asp.net controls such as textboxes and a submit button, to take inputs from users and click on the send button. We will also add a label control to show the status of whether the message has been send to the email address provided by the user after we click the send button.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="aspnet_mail.index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <table align="center" width="60%">
            <tr>
                <td>to</td>
                <td>
                    <asp:TextBox ID="to" runat="server" Width="99%"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidatorTo" runat="server" ErrorMessage="Field is Required" ForeColor="Red" ControlToValidate="to"></asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator ID="ExpValidatorTo" runat="server" ErrorMessage="Email is invalid" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="to"></asp:RegularExpressionValidator>
                </td>
            </tr>
            <!-- ... (similar formatting for other form elements) ... -->
        </table>
    </form>
</body>
</html>

Here we are adding a table and setting its width. Inside the table, we can add asp.net controls to take inputs from the user and a send button to handle an event when the send button is clicked.

Inside index.aspx we have the following 4 fields.

  • to
  • from
  • subject
  • message

When the user clicks the "Send" button, the mail will be sent to the specified mail address that you provide in the "to" textbox.

Inside controls, there is an instance ID, through which we can reference text inside asp.net controls anywhere in our application. At last, we have a label that will be updated each time we try to send an email.

The RequiredFieldValidator is also included in the above code to validate all the text boxes. If we leave the text boxes empty and try to click on the send button, then an error message “Field is Required” should return for each and every textbox.

The RegularExpressionValidator is also included in the code above to validate text boxes that take email ID as input. If an email address does not match with the regular expression mentioned in the ValidationExpression property of RegularExpressionValidator control then an error message “Email is invalid” will return.

To send additional files as an attachment, we are using FileUpload control and to attach multiple files, we can set AllowMultiple property foFileUpload control to true.

Now to handle an event when the send button is clicked we can write C# code inside index.aspx.cs file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace aspnet_mail
{
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e) { }

        protected void send_click(object sender, EventArgs e)
        {
            try
            {
                MailMessage message = new MailMessage(to.Text, from.Text, subject.Text, body.Text);

                if (upload.HasFile)
                {
                    HttpFileCollection fc = Request.Files;

                    for (int i = 0; i <= fc.Count - 1; i++)
                    {
                        HttpPostedFile pf = fc[i];
                        Attachment attach = new Attachment(pf.InputStream, pf.FileName);
                        message.Attachments.Add(attach);
                    }
                }

                SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
                client.EnableSsl = true;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = false;
                client.Credentials = new System.Net.NetworkCredential("[email protected]", "12345");

                client.Send(message);
                status.Text = "Message was sent successfully";
            }
            catch (Exception ex)
            {
                status.Text = ex.StackTrace;
            }
        }
    }
}

Inside insideindex.aspx.cs file, there is a class called MailMessage which represents an email message that can be sent using the SmtpClient class.

Inside the MailMessage class, the constructor has been invoked by the instance message. The constructor contains certain properties which are passed as parameters,

  • To
  • From
  • Subject
  • Body

To attach a file or multiple files to an email message, we are using the Attachment class which represents an attachment to an email.

if (upload.HasFile)
{
    HttpFileCollection fc = Request.Files;
    for (int i = 0; i <= fc.Count - 1; i++)
    {
        HttpPostedFile pf = fc[i];
        Attachment attach = new Attachment(pf.InputStream, pf.FileName);
        message.Attachments.Add(attach);
    }
}

Here, we are using for loop to attach multiple files. To add an attachment to a mail message, we can add it to the MailMessage.Attachments collection.

For sending email we need an SMTP Server, so in ASP.Net, we have the SmtpClient class, using that class object we set its properties for the SMTP settings.

SmtpClient client = new SmtpClient("smtp.gmail.com", 587);

Here client is an instance of the SmtpClient class to which Host and port properties are being passed.

smtp.gmail.com, is the SMTP Host address of Gmail, if you want to use any other SMTP host service please add a different SMTP host protocol, for example for Hotmail it is smtp.live.com.

587 is the port for Gmail, so for any other service port, you have to change the port accordingly.

client.Credentials = new System.Net.NetworkCredential("username", "password");

The credentials property specifies the network credentials of your Gmail ID so here we can add a username and password.

client.EnableSsl = true;

For a secure mail server, we need to enable the SSL layer to encrypt the connection.

client.Send(message);

The send method is used to send the specified message to an SMTP server for delivery.

Output

After filling in all the information, if you click on the send button the output will be as follows.

Sending an E-Mail Using ASP.NET With C#

If we leave all the fields blank and click on the send button then an error message “Field is Required” will return for each and every blank field.

Sending an E-Mail Using ASP.NET With C#

If an email address does not match with the regular expression mentioned in validationexpression property of RegularExpressionValidator control then an error message “Email is invalid” will return.

Sending an E-Mail Using ASP.NET With C#

Summary

In this article, I explained SmtpClient and MailMessage classes along with their properties, methods, and constructors to demonstrate how we can create web applications to send email by using the Simple Mail Transfer Protocol (SMTP). I also created a web form inside the ASP.NET web application to send emails to the email address provided by users as input. The RequiredFieldValidator is also included in the above code to validate all the textboxes. The RegularExpressionValidator is also included in the code above to validate text boxes that take email ID as input. To attach a file or multiple files to an email message, we are using Attachment class which represents an attachment to an email. A proper coding snippet along with an output screenshot has been provided to implement the functionality of sending messages to email addresses provided by users.


Recommended Free Ebook
Similar Articles