Sending Emails in ASP - NET Using C#
Sending Emails in ASP - NET Using C#
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,
Gets or sets the name or IP address of the host used for SMTP
Host
transactions.
Port Gets or sets the port used for SMTP transactions.
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.
To Gets the address collection that contains the recipients of this email message.
Subject Gets or sets the subject line for this email message.
The MailMessage class constructors along with their overloads are as follows,
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,
Gets or sets the MIME content type name value in the content type
Name
associated with this attachment.
ContentDispositio
Gets the MIME content disposition for this attachment.
n
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.
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.
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.
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 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) {}
12. try {
13. MailMessage message = newMailMessage(to.Text, fro
m.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.Inpu
tStream, 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.Networ
k;
25. client.UseDefaultCredentials = false;
26. client.Credentials = newSystem.Net.NetworkCredent
ial("[email protected]", "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.FileNa
me);
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.
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.
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,
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.
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.
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