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 account in case of login functionality in asp.net project. Therefore in this article, I will be explaining how an email can be send using ASP.NET with C#. I will be working on window forms of asp.net web application.I will be demonstrating how to use asp.net to build 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.Mail namespace contains classes used to send electronic mail to a Simple Mail Transfer Protocol (SMTP) server for delivery.I will be using SmtpClient and MailMessage todemonstrate how we can create web applications tosend email by using the Simple Mail Transfer Protocol (SMTP).
 

SmtpClient Class

 
The SmtpClient Class belongs to the System.Net.Mail namespace. The SmtpClient class Allowsapplications 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 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 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 messages that can be sent using 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 MailMessage class,
 
To
 
Gets the address collection that contains the recipients of this email message.
 
From
 
Gets or sets from 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 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#
 
New Project dialogue will open, select ASP.NET Web Application. Specify the name of the project and click on OK button.
 
A new dialogue will open, select 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 user 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, click on New Item.
 
A dialogue box named Add New Item will open, click on web option on the left side of the dialogue box. Select Web Form from the given options and specify the name of the form and click on Add button.
 
Sending an E-Mail Using ASP.NET With C#
 
Inside index.aspx web form which runs on server, we will add asp.net controls such as textboxes and submit button, to take inputs from user and click on send button. We will also add a label control to show status of whether the message has been send on the email address provided by user after we click send button.
  1. <%@PageLanguage="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="aspnet_mail.index"%>  
  2. <!DOCTYPE html>  
  3. <html  
  4.     xmlns="http://www.w3.org/1999/xhtml">  
  5.     <head runat="server">  
  6.         <title></title>  
  7.     </head>  
  8.     <body>  
  9.         <form id="form1" runat="server">  
  10.             <table align="center" width="60%">  
  11.                 <tr>  
  12.                     <td>to</td>  
  13.                     <td>  
  14.                         <asp:TextBox ID="to" runat="server" Width="99%">  
  15.                         </asp:TextBox>  
  16.                         <asp:RequiredFieldValidator ID="RequiredFieldValidatorTo" runat="server" ErrorMessage="Field is Required"ForeColor="Red"ControlToValidate="to">  
  17.                         </asp:RequiredFieldValidator>  
  18.                         <asp:RegularExpressionValidator ID="ExpValidatorTo" runat="server" ErrorMessage="Email is invalid"  
  19. ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="to">  
  20.                         </asp:RegularExpressionValidator>  
  21.                     </td>  
  22.                 </tr>  
  23.                 <tr>  
  24.                     <td>from</td>  
  25.                     <td>  
  26.                         <asp:TextBox ID="from" runat="server" Width="99%">  
  27.                         </asp:TextBox>  
  28.                         <asp:RequiredFieldValidator ID="RequiredFieldValidatorFrom" runat="server"  
  29. ErrorMessage="Field is Required" ForeColor="Red" ControlToValidate="from">  
  30.                         </asp:RequiredFieldValidator>  
  31.                         <asp:RegularExpressionValidator ID="ExpValidatorFrom" runat="server"  
  32. ErrorMessage="Email is invalid"  
  33. ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"ControlToValidate="from">  
  34.                         </asp:RegularExpressionValidator>  
  35.                     </td>  
  36.                 </tr>  
  37.                 <tr>  
  38.                     <td>subject</td>  
  39.                     <td>  
  40.                         <asp:TextBox ID="subject" runat="server" Width="99%">  
  41.                         </asp:TextBox>  
  42.                         <asp:RequiredFieldValidator ID="RequiredFieldValidatorsubject" runat="server"  
  43. ErrorMessage="Field is Required" ForeColor="Red" ControlToValidate="subject">  
  44.                         </asp:RequiredFieldValidator>  
  45.                     </td>  
  46.                 </tr>  
  47.                 <tr>  
  48.                     <td>body</td>  
  49.                     <td>  
  50.                         <asp:TextBox ID="body" runat="server" Width="99%" Height="150px" TextMode="MultiLine">  
  51.                         </asp:TextBox>  
  52.                         <asp:RequiredFieldValidator ID="RequiredFieldValidatorbody" runat="server"  
  53. ErrorMessage="Field is Required" ForeColor="Red" ControlToValidate="body">  
  54.                         </asp:RequiredFieldValidator>  
  55.                     </td>  
  56.                 </tr>  
  57.                 <tr>  
  58.                     <td>file upload</td>  
  59.                     <td>  
  60.                         <asp:FileUpload runat="server" AllowMultiple="true" ID="upload">  
  61.                         </asp:FileUpload>  
  62.                     </td>  
  63.                 </tr>  
  64.                 <tr>  
  65.                     <td></td>  
  66.                     <td>  
  67.                         <asp:Button ID="send" OnClick="send_click" runat="server" Text="send"/>  
  68.                     </td>  
  69.                 </tr>  
  70.                 <tr>  
  71.                     <td></td>  
  72.                     <td>  
  73.                         <asp:Label ID="status" runat="server">  
  74.                         </asp:Label>  
  75.                     </td>  
  76.                 </tr>  
  77.             </table>  
  78.         </form>  
  79.     </body>  
  80. </html>  
Here we are adding a table and setting its width. Inside table we can add asp.net controls to take inputs from user and a send button to handle an event when 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 instance id, through which we can reference text inside asp.net controls anywhere in our application. At last we have 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 textboxes. If we leave the textboxes empty and try to click on 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 which takes email id as input. 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.
 
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 send button is clicked we can write C# code inside index.aspx.cs file.
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Net.Mail;    
  5. using System.Web;    
  6. using System.Web.UI;    
  7. using System.Web.UI.WebControls;    
  8. namespace aspnet_mail {    
  9.     public partial class index: System.Web.UI.Page {    
  10.         protected void Page_Load(object sender, EventArgs e) {}    
  11.         protected void send_click(object sender, EventArgs e) {    
  12.             try {    
  13.                 MailMessage message = newMailMessage(to.Text, from.Text, subject.Text, body.Text);    
  14.                 if (upload.HasFile) {    
  15.                     HttpFileCollection fc = Request.Files;    
  16.                     for (inti = 0; i <= fc.Count - 1; i++) {    
  17.                         HttpPostedFile pf = fc[i];    
  18.                         Attachment attach = newAttachment(pf.InputStream, pf.FileName);    
  19.                         message.Attachments.Add(attach);    
  20.                     }    
  21.                 }    
  22.                 SmtpClient client = newSmtpClient("smtp.gmail.com", 587);    
  23.                 client.EnableSsl = true;    
  24.                 client.DeliveryMethod = SmtpDeliveryMethod.Network;    
  25.                 client.UseDefaultCredentials = false;    
  26.                 client.Credentials = newSystem.Net.NetworkCredential("abc@gmail.com""12345");    
  27.                 client.Send(message);    
  28.                 status.Text = "message was sent successfully";    
  29.             } catch (Exception ex) {    
  30.                 status.Text = ex.StackTrace;    
  31.             }    
  32.         }    
  33.     }    
  34. }  
Inside insideindex.aspx.cs file, there is class called MailMessage which represents an email messages that can be sent using SmtpClient class.
 
Inside 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 Attachment class which represents an attachment to an email.
  1. if (upload.HasFile) {  
  2.     HttpFileCollection fc = Request.Files;  
  3.     for (inti = 0; i <= fc.Count - 1; i++) {  
  4.         HttpPostedFile pf = fc[i];  
  5.         Attachment attach = newAttachment(pf.InputStream, pf.FileName);  
  6.         message.Attachments.Add(attach);  
  7.     }  
  8. }  
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 a SMTP Server, so in ASP.Net we have the SmtpClient class, using that class object we set its properties for the SMTP settings.
  1. SmtpClient client = newSmtpClient("smtp.gmail.com", 587);  
Here client is an instance of 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.
  1. client.Credentials = newSystem.Net.NetworkCredential("username""password");  
Credentials property specifies the network credentials of your Gmail Id so here we can add username and password.
  1. client.EnableSsl = true;  
For a secure mail server, we need to enable the SSL layer to encrypt the connection.
  1. client.Send(message); 
Send method is used to Sends the specified message to an SMTP server for delivery.
 
Output
 
After filling all the information, if click on send button then output will be as follows,
 
Sending an E-Mail Using ASP.NET With C#
 
If we leave all the fields blank and click on 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 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 which takes 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. Proper coding snippet along with output screenshot has been provided to implement the functionality of sending messages to email address provided by users.