ASP.NET – SMTP E-Mail | Using ASP.NET To Send Email


Email serves as a ubiquitous, asynchronous notification and information distribution system. Not surprisingly, there are
many web development scenarios where server-side code needs to generate an email and scuttle it off to the intended
recipient. The email may be destined for a user of the website, informing them of their newly created user account,
reminding them of their forgotten password, or emailing them an invoice. Or it may be destined for a web developer or
site administrator, providing information of an unhandled exception that just transpired or user feedback.
OR
E-mail is one of the most common and reliable methods of communication for both personal and business purposes. It also
plays an important role in each and every Web site. This role will be in the type of automated e-mails from the server after
posting information from a form. You may have noticed these types of e-mails while registering on a site. As soon as you
post the form, the server will send an e-mail asking you to confirm either your registration or with the information you
entered. If you have to confirm the registration, the server will send you a long URL that you have to click to proceed
further with the registration process. A classic example of this functionality is ASP.NET forums. As soon as you register,
you will be e-mailed a random password. You will also get e-mails after your post has been accepted by a moderator or if
somebody replies to your post. If you are wondering that this is a server magic—it is not. The whole process is made
possible with the help of server-side programming framework such as ASP and ASP.NET.
Classic ASP provided a component named CDONTS that a developer should use intelligently to provide e-mail functionality
on his or her applications. But this component lacked major functionalities. You can easily send an e-mail, but the process
is very difficult for sending e-mails with attachments, HTML versions, and so forth. Almost all server-side languages provide
some sort of solution for achieving these tasks. But, ASP.NET simplified the work of developers with the introduction of a
special .NET namespace called System.Web.Mail. Moreover, it is very tedious to upload a file to a server with ASP. You
have to depend upon third-party components. ASP.NET ships with a cute built-in uploading capability with which your users
can easily upload their files. They can also send the file as an attachment along with their e-mails. In this document, you
will learn how to send different types of e-mails with ASP.NET.
To send e-mails, you should require access to a server with .NET Framework and SMTP enabled on it. SMTP stands for
Simple Mail Transfer Protocol and e-mails are sent using this protocol.
The .NET Framework supplies a SMTP class that enables you to send a simple e-mail message. If you have to send an email
with added functionalities, you have to make use of the MailMessage class. With the help of this class, you can add
attachments, set priorities, and much more, very easily. You can also send HTML e-mail using this class.
Fortunately, ASP.NET makes sending email a breeze. The .NET Framework version 1.x included a number of classes in
the System.Web.Mail namespace that allowed programmatically sending an email with a few scant lines of code. While
this namespace and these classes still exist in the .NET Framework version 2.0, they have been deprecated in favor of new
mail-related classes found in the System.Net.Mail namespace.
In order to send an email from an ASP.NET Web page, we need to use the SmtpMail class found in the System.Web.Mail
namespace, which contains a static method Send().
OR
In order to send an email from an ASP.NET Web page, we need to use the SmtpClient class found in the System.Net.Mail
namespace, which contains a method Send().
SmtpMail Class Provides properties and methods for sending messages using the Collaboration Data Objects for
Windows 2000 (CDOSYS) message component. Recommended alternative: System.Net.Mail.
SmtpClient Class allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP).
Copyright © 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.
P a g e | 2
In this document we'll look at the classes in the System.Net.Mail namespace and see how to send an email from an
ASP.NET Page.
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 following major 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 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 classes shown in the following table are used to construct e-mail messages that can be sent using SmtpClient.
Class Description
Attachment Represents file attachments. This class allows you to attach files, streams, or text to an e-mail message.
MailAddress Represents the e-mail address of the sender and recipients.
MailMessage Represents an e-mail message.
To construct and send an e-mail message by using SmtpClient, you must specify the following information:
 The SMTP host server that you use to send e-mail. See the Host and Port properties.
 Credentials for authentication, if required by the SMTP server. See the Credentials property.
 The e-mail address of the sender. See the Send and SendAsync methods that take a from parameter. Also see
the MailMessage.From property.
 The e-mail address or addresses of the recipients. See the Send and SendAsync methods that take
a recipient parameter. Also see the MailMessage.To property.
 The message content. See the Send and SendAsync methods that take a body parameter. Also see
the MailMessage.Body property.
To include an attachment with an e-mail message, first create the attachment by using the Attachment class, and then add
it to the message by using the MailMessage.Attachments property. Depending on the e-mail reader used by the recipients
and the file type of the attachment, some recipients might not be able to read the attachment. For clients that cannot display
the attachment in its original form, you can specify alternate views by using the MailMessage.AlternateViews property.
You can use the application or machine configuration files to specify default host, port, and credentials values for
all SmtpClient objects.
Copyright © 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.
P a g e | 3
SmtpClient Class:
Constructors:
Name Description
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 e-mail by using the specified SMTP
server.
SmtpClient(String,
Int32)
Initializes a new instance of the SmtpClient class that sends e-mail by using the specified SMTP
server and port.
Properties:
Name Description
ClientCertificates Specify which certificates should be used to establish the Secure Sockets Layer (SSL)
connection.
Credentials Gets or sets the credentials used to authenticate the sender.
DeliveryFormat Gets or sets the delivery format used by SmtpClient to send e-mail.
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.
PickupDirectoryLocation Gets or sets the folder where applications save mail messages to be processed by the local
SMTP server.
Port Gets or sets the port used for SMTP transactions.
ServicePoint Gets the network connection used to transmit the e-mail message.
TargetName Gets or sets the Service Provider Name (SPN) to use for authentication when using
extended protection.
Timeout Gets or sets a value that specifies the amount of time after which a synchronous Send call
times out.
UseDefaultCredentials Gets or sets a Boolean value that controls whether the DefaultCredentials are sent with
requests.
Copyright © 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.
P a g e | 4
Methods:
Name Description
Send(MailMessage) Sends the specified message to an SMTP server for delivery.
Send(String, String, String, String) Sends the specified e-mail message to an SMTP server for delivery. The message
sender, recipients, subject, and message body are specified using String objects.
SendAsync(MailMessage, Object) Sends the specified e-mail message to an SMTP server for delivery. This method
does not block the calling thread and allows the caller to pass an object to the
method that is invoked when the operation completes.
SendAsync(String, String, String,
String, Object)
Sends an e-mail message to an SMTP server for delivery. The message sender,
recipients, subject, and message body are specified using String objects. This
method does not block the calling thread and allows the caller to pass an object to
the method that is invoked when the operation completes.
SendAsyncCancel Cancels an asynchronous operation to send an e-mail message.
SendMailAsync(MailMessage) Sends the specified message to an SMTP server for delivery as an asynchronous
operation.
SendMailAsync(String, String,
String, String)
Sends the specified message to an SMTP server for delivery as an asynchronous
operation. . The message sender, recipients, subject, and message body are specified
using String objects.
Events:
Name Description
SendCompleted Occurs when an asynchronous e-mail send operation completes.
MailMessage Class:
Represents an e-mail message that can be sent using the SmtpClient class.
Constructors:
Name Description
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.
Copyright © 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.
P a g e | 5
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.
Properties
Name Description
AlternateViews Gets the attachment collection used to store alternate forms of the message body.
Attachments Gets the attachment collection used to store data attached to this e-mail message.
Bcc Gets the address collection that contains the blind carbon copy (BCC) recipients for this
e-mail message.
Body Gets or sets the message body.
BodyEncoding Gets or sets the encoding used to encode the message body.
BodyTransferEncoding Gets or sets the transfer encoding used to encode the message body.
CC Gets the address collection that contains the carbon copy (CC) recipients for this e-mail
message.
DeliveryNotificationOptions Gets or sets the delivery notifications for this e-mail message.
From Gets or sets the from address for this e-mail message.
Headers Gets the e-mail headers that are transmitted with this e-mail message.
HeadersEncoding Gets or sets the encoding used for the user-defined custom headers for this e-mail
message.
IsBodyHtml Gets or sets a value indicating whether the mail message body is in Html.
Priority Gets or sets the priority of this e-mail message.
ReplyTo Obsolete. Gets or sets the ReplyTo address for the mail message.
ReplyToList Gets or sets the list of addresses to reply to for the mail message.
Copyright © 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.
P a g e | 6
Sender Gets or sets the sender's address for this e-mail message.
Subject Gets or sets the subject line for this e-mail message.
SubjectEncoding Gets or sets the encoding used for the subject content for this e-mail message.
To Gets the address collection that contains the recipients of this e-mail message.
Note:
Instances of the MailMessage class are used to construct e-mail messages that are transmitted to an SMTP server for
delivery using the SmtpClient class.
The sender, recipient, subject, and body of an e-mail message may be specified as parameters when a MailMessage is used
to initialize a MailMessageobject. These parameters may also be set or accessed using properties on the MailMessage object.
Attachment Class:
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.
MailAddress Class:
Represents the address of an electronic mail sender or recipient.
The MailAddress class is used by the SmtpClient and MailMessage classes to store address information for e-mail messages.
A mail address is composed of a User name, Host name and optionally, a DisplayName. The DisplayName can contain non-
ASCII characters if you encode them.
Sending e-mails with ASP.NET is pretty straight forward. The .NET framework comes with an entire namespace for handling
e-mails, the System.Net.Mail namespace. In the following examples, we will use two classes from this namespace: The
MailMessage class, for the actual e-mail, and the SmtpClient class, for sending the e-mail.
As you may be aware, mails are sent through an SMTP server, and to send mails with the .NET framework, you will need
access to an SMTP server. If you're testing things locally, the company that supplies your with Internet access, will usually
have an SMTP server that you can use, and if you wish to use one of these examples on your actual website, the company
that hosts your website will usually have an SMTP server that you can use. Go through the support pages to find the actual
address - it's usually something along the lines of smtp.your-isp.com or mail.your-isp.com.
Example1: Create an example of sending email from ASP.NET Page locally that stored in the specified pickup folder of
local Smtp Server on IIS:
Copyright © 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.
P a g e | 7
IIS Configuration:
Your local IIS instance has to be properly configured in order to successfully send an email message through its SMTP mail
server.
Open IIS Manager, Locate your website, and then open SMTP E-mail feature to configure it as following:
Now click apply link from the Action at right side of the window to save the current changes in an application’s configuration
file i.e. web.config as following:
<configuration>
<system.net>
<mailSettings>
<smtp deliveryMethod="SpecifiedPickupDirectory" />
</mailSettings>
</system.net>
</configuration>
Html Source:
<h1 style="text-align: center">Sending Email</h1>
<asp:Label ID="lblStatus" runat="server" />
<br />
<b>From:</b>
<br />
<asp:TextBox ID="txtFrom" runat="server" Width="300"></asp:TextBox>
<br />
<b>To:</b>
<br />
<asp:TextBox ID="txtTo" runat="server" Width="300"></asp:TextBox>
<br />
<b>Subject:</b>
<br />
<asp:TextBox ID="txtSubject" runat="server" Width="300"></asp:TextBox>
<br />
<b>Message:</b>
<br />
<asp:TextBox ID="txtMessage" runat="server" TextMode="MultiLine" Rows="10" Columns="100"></asp:TextBox>
<br />
<asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" />
Copyright © 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.
P a g e | 8
Code View:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class SendEmail1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
txtFrom.Focus();
}
protected void btnSend_Click(object sender, EventArgs e)
{
try
{
string from = txtFrom.Text.Trim();
string to = txtTo.Text.Trim();
string subject = txtSubject.Text.Trim();
string message = txtMessage.Text.Trim();
SmtpClient objSmtpClient = new SmtpClient();
objSmtpClient.Host = "localhost";
objSmtpClient.Port = 25;
objSmtpClient.Send(from, to, subject, message);
lblStatus.Text = "<b style='color:green'>Email has been sent successfully!!!</b>";
}
catch (SmtpException ex)
{
lblStatus.Text = "<b style='color:red'>" + ex.Message + "</b>";
}
}
}
Output:
Copyright © 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.
P a g e | 9
Example2: Create an example of sending email from ASP.NET Page locally, in which construct email using MailMessage
Class with Attachment Class to attach the file.
HTML Source:
<h1 style="text-align: center">Sending Email</h1>
<asp:Label ID="lblStatus" runat="server" />
<br />
<b>From:</b>
<br />
<asp:TextBox ID="txtFrom" runat="server" Width="300"></asp:TextBox>
<br />
<b>To:</b>
<br />
<asp:TextBox ID="txtTo" runat="server" Width="300"></asp:TextBox>
<br />
<b>Subject:</b>
<br />
<asp:TextBox ID="txtSubject" runat="server" Width="300"></asp:TextBox>
<br />
<b>Message:</b>
<br />
<asp:TextBox ID="txtMessage" runat="server" TextMode="MultiLine" Rows="9" Columns="100"></asp:TextBox>
<br />
<b>Attachment:</b>
<br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" />
Code View:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
Copyright © 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.
P a g e | 10
public partial class SendEmail2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
txtFrom.Focus();
}
protected void btnSend_Click(object sender, EventArgs e)
{
try
{
MailMessage objMailMessage = new MailMessage();
objMailMessage.From = new MailAddress(txtFrom.Text.Trim());
objMailMessage.To.Add(new MailAddress(txtTo.Text.Trim()));
objMailMessage.Subject = txtSubject.Text.Trim();
objMailMessage.Body = txtMessage.Text.Trim();
objMailMessage.IsBodyHtml = false;
if (FileUpload1.HasFile)
objMailMessage.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream,
FileUpload1.FileName));
objMailMessage.Priority = MailPriority.High;
SmtpClient objSmtpClient = new SmtpClient();
objSmtpClient.Host = "localhost";
objSmtpClient.Port = 25;
objSmtpClient.Send(objMailMessage);
lblStatus.Text = "<b style='color:green'>Email has been sent successfully!!!</b>";
}
catch (SmtpException ex)
{
lblStatus.Text = "<b style='color:red'>" + ex.Message + "</b>";
}
}
}
Output:
Copyright © 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.
P a g e | 11
Example3: Create an example to Send email using Gmail SMTP Mail Server from ASP.Net Page.
In this document I will explain how to send email using Gmail SMTP Server in ASP.Net. To send email with Gmail SMTP
Server, you will need to use an email address and password of a valid Gmail account and along with that you will need the
Gmail SMTP Mail Server settings.
Gmail SMTP Mail Server Details:
Host: smtp.gmail..com
Port: 587
HTML Source:
<h1 style="text-align: center">Sending Email</h1>
<asp:Label ID="lblStatus" runat="server" />
<br />
<b>From:</b>
<br />
<asp:TextBox ID="txtFrom" runat="server" Width="300"></asp:TextBox>
<br />
<b>Password:</b>
<br />
<asp:TextBox ID="txtPassword" runat="server" Width="300" TextMode="Password"></asp:TextBox>
<br />
<b>To:</b>
<br />
<asp:TextBox ID="txtTo" runat="server" Width="300"></asp:TextBox>
<br />
<b>Subject:</b>
<br />
<asp:TextBox ID="txtSubject" runat="server" Width="300"></asp:TextBox>
<br />
<b>Message:</b>
<br />
<asp:TextBox ID="txtMessage" runat="server" TextMode="MultiLine" Rows="5" Columns="100"></asp:TextBox>
<br />
<b>Attachment:</b>
<br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<br />
<asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" />
Copyright © 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.
P a g e | 12
Code View:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class SendEmail3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
txtFrom.Focus();
}
protected void btnSend_Click(object sender, EventArgs e)
{
try
{
MailMessage objMailMessage = new MailMessage();
objMailMessage.From = new MailAddress(txtFrom.Text.Trim());
objMailMessage.To.Add(new MailAddress(txtTo.Text.Trim()));
objMailMessage.Subject = txtSubject.Text.Trim();
objMailMessage.Body = txtMessage.Text.Trim();
objMailMessage.IsBodyHtml = false;
if (FileUpload1.HasFile)
objMailMessage.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream,
FileUpload1.FileName));
objMailMessage.Priority = MailPriority.High;
System.Net.NetworkCredential objNetworkCredential = new System.Net.NetworkCredential(txtFrom.Text.Trim(),
txtPassword.Text.Trim());
SmtpClient objSmtpClient = new SmtpClient();
objSmtpClient.Host = "smtp.gmail.com";
objSmtpClient.Port = 587;
objSmtpClient.Credentials = objNetworkCredential;
objSmtpClient.EnableSsl = true;
objSmtpClient.Send(objMailMessage);
lblStatus.Text = "<b style='color:green'>Email has been sent successfully!!!</b>";
}
catch (SmtpException ex)
{
lblStatus.Text = "<b style='color:red'>" + ex.Message + "</b>";
}
}
}
Copyright © 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.
P a g e | 13
Output:
Example4: Create an example to Send email using Gmail SMTP Mail Server from ASP.Net Page and specify the Gmail
SMTP Mail Server Details (Such as From, Host, & Port) including NetworkCredential (Such as User Name & Password) in an
application’s web.config file.
HTML Source:
<h1 style="text-align: center">Sending Email</h1>
<asp:Label ID="lblStatus" runat="server" />
<br />
<b>To:</b>
<br />
<asp:TextBox ID="txtTo" runat="server" Width="600"></asp:TextBox>
<br />
<b>Subject:</b>
<br />
<asp:TextBox ID="txtSubject" runat="server" Width="300"></asp:TextBox>
<br />
<b>Message:</b>
<br />
<asp:TextBox ID="txtMessage" runat="server" TextMode="MultiLine" Rows="10" Columns="100"></asp:TextBox>
<br />
<b>Attachment:</b>
<br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" />
Copyright © 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.
P a g e | 14
Web.Config:
<configuration>
<appSettings>
<add key="From" value="rakesh.netatnit@gmail.com" />
<add key="Host" value="smtp.gmail.com" />
<add key="Port" value="587" />
</appSettings>
<system.net>
<mailSettings>
<smtp>
<network defaultCredentials="false" host="smtp.gmail.com" port="587"
userName="rakesh.netatnit@gmail.com" password="******" />
</smtp>
</mailSettings>
</system.net>
</configuration>
Code View:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Configuration;
public partial class Default121 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
txtTo.Focus();
}
protected void btnSend_Click(object sender, EventArgs e)
{
try
{
MailMessage objMailMessage = new MailMessage();
objMailMessage.From = new MailAddress(ConfigurationManager.AppSettings["From"].ToString());
string[] strToMails = txtTo.Text.Trim().Split(',');
if (strToMails.Length > 0)
{
foreach (string toMail in strToMails)
{
objMailMessage.To.Add(new MailAddress(toMail));
}
}
objMailMessage.Subject = txtSubject.Text.Trim();
objMailMessage.Body = txtMessage.Text.Trim();
objMailMessage.IsBodyHtml = false;
if (FileUpload1.HasFile)
Copyright © 2015 - 2016 https://www.facebook.com/rakeshdotnet All Rights Reserved.
P a g e | 15
objMailMessage.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream,
FileUpload1.FileName));
objMailMessage.Priority = MailPriority.High;
SmtpClient objSmtpClient = new SmtpClient();
objSmtpClient.Host =ConfigurationManager.AppSettings["Host"].ToString();
objSmtpClient.Port = int.Parse(ConfigurationManager.AppSettings["Port"].ToString());
objSmtpClient.EnableSsl = true;
objSmtpClient.Send(objMailMessage);
lblStatus.Text = "<b style='color:green'>Email has been sent successfully!!!</b>";
}
catch (SmtpException ex)
{
lblStatus.Text = "<b style='color:red'>" + ex.Message + "</b>";
}
}
}
Output:
Note: If you have enabled two-factor authentication (also known as twostep
verification) on your GMail account, you must generate an applicationspecific
password and use that newly generated password to authenticate via
SMTP.
Share on Google Plus

About Unknown

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment