If you
want to add functionality of sending email for your ASP.Net web application one
way is to configure your own SMTP (for large application, companies configure
their own mail server), however if you have not access to any SMTP server, don’t
worry Google is there to rescue the things. You can send email through Gmail
SMTP Mail Server; for this you just need to use an email address and password
of a valid Gmail account and the Gmail SMTP Mail Server settings.
In this
article I will explain how to send email in ASP.Net using Gmail SMTP Server.
Before
proceeding further let’s understand the required MailMessage Class Properties:
Property
|
Description
|
From
|
Email address of
Sender
|
To
|
Email Address of Recipient(s)
|
CC
|
Carbon Copies Email
addresses (if any)
|
BCC
|
Blind Carbon Copies
Email addresses (if any)
|
Subject
|
Subject of the Email
|
IsBodyHtml
|
Boolean property to
specify whether body contains text or HTML.
|
Attachments
|
File Attachments (if
any)
|
ReplyTo
|
ReplyTo Email
address.
|
To send
an email we need to create object of SmtpClient,
mentioned below are properties of SmtpClient:
Property
|
Description
|
Host
|
SMTP Server URL, for
Gmail use: smtp.gmail.com
|
EnableSsl
|
Boolean property to
specify whether your host accepts SSL Connections, for Gmail: True
|
UseDefaultCredentials
|
Set to True in order
to allow authentication based on the Credentials of the Account used to send
emails.
|
Credentials
|
Login credentials
for the SMTP server, for Gmail: use valid email address and password)
|
Port
|
Port Number of the
SMTP server, for Gmail: 587
|
We have
now basic understanding of MailMessage Class and SmtpClient. So let’s move
ahead and write the logic to send the email.
HTML Form
First of
all let’s create one form with fields as Recipient Email, Subject, Email Body, file
attachment, email address and password (of your valid Gmail account) and a
Button to send the email.
<h2 style="margin-bottom: 20px;">
Send Email !!!
</h2>
<div style="float:right; color:red">
*required
</div>
<table class="emailForm" cellpadding="0" cellspacing="0">
<tr>
<td>
To:
</td>
<td>
<asp:TextBox ID="ToTextBox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="rvTo" ControlToValidate="ToTextBox"
ErrorMessage="*required" ForeColor="Red" Display="Dynamic">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revTo"
runat="server"
ControlToValidate="ToTextBox"
ForeColor="Red" Display="Dynamic" ErrorMessage="* Invalid Email Address" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
Subject:
</td>
<td>
<asp:TextBox ID="SubjectTextBox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="rvSubject" ControlToValidate="SubjectTextBox"
ErrorMessage="*required" ForeColor="Red" Display="Dynamic">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td style="vertical-align: top;">
Body:
</td>
<td>
<asp:TextBox ID="BodyTextBox" runat="server" TextMode="MultiLine" Height="100" Width="300"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="rvBody" ControlToValidate="BodyTextBox"
ErrorMessage="*required" ForeColor="Red" Display="Dynamic">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
Attach File:
</td>
<td>
<asp:FileUpload ID="AttachmentFileUpload" runat="server"
/>
</td>
</tr>
<tr>
<td colspan="2">
<h3>
Enter Your Gmail UserName and
Password Details To Send the Email through Gmail SMTP !!!
</h3>
</td>
</tr>
<tr>
<td>
Email Address:
</td>
<td>
<asp:TextBox ID="EmailTextBox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="rvEmail" ControlToValidate="EmailTextBox"
ErrorMessage="*required" ForeColor="Red" Display="Dynamic">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revEmail"
runat="server"
ControlToValidate="EmailTextBox"
ForeColor="Red" Display="Dynamic" ErrorMessage="* Invalid Email Address" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
Password:
</td>
<td>
<asp:TextBox ID="PasswordTextBox" runat="server"
TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="rvPassword" ControlToValidate="PasswordTextBox"
ErrorMessage="*required" ForeColor="Red" Display="Dynamic">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="SendEmailButton" Text="Send Email"
OnClick="SendEmailButtonOnClick"
runat="server" />
</td>
</tr>
</table>
|
Use Gmail SMTP Account to send the
Email:
Below is
the code to send email using Gmail SMTP server in ASP.Net.
The
Recipient email address (to), the Sender email address (from), Subject, Body
and file attachment is populated from their respective fields. And we set these
values into an object of the MailMessage class.
Then we create
an object of the SmtpClient class, by using the settings of the Mail Server, in
this example we are using Gmail as the Mail Server, so we will set the Mail
Settings of the Gmail SMTP Server.
//Namespace required
for this example.
using System.IO;
using System.Net;
using System.Net.Mail;
//Button Click Event
to send email.
protected void
SendEmailButtonOnClick(object sender, EventArgs e)
{
using (var message = new MailMessage(EmailTextBox.Text, ToTextBox.Text))
{
message.Subject =
SubjectTextBox.Text;
message.Body = BodyTextBox.Text;
message.IsBodyHtml = false;
if
(AttachmentFileUpload.HasFile)
{
var
fileName = Path.GetFileName(AttachmentFileUpload.PostedFile.FileName);
message.Attachments.Add(new Attachment(AttachmentFileUpload.PostedFile.InputStream,
fileName));
}
var
smtp = new SmtpClient
{Host = "smtp.gmail.com",
EnableSsl = true, UseDefaultCredentials = true};
var
networkCred = new NetworkCredential(EmailTextBox.Text,
PasswordTextBox.Text);
smtp.Credentials = networkCred;
smtp.Port = 587;
//Send
Email.
smtp.Send(message);
//Clear
fields.
ToTextBox.Text =
SubjectTextBox.Text =
BodyTextBox.Text =
EmailTextBox.Text =
PasswordTextBox.Text = string.Empty;
ClientScript.RegisterStartupScript(GetType(), "alert",
"alert('Your email is sent.');",
true);
}
}
|
Note: For the article I have set
SmtpClient properties through the code, however you can set these properties
through web.config file as mentioned below(in large application we define properties in
web.config and then create the object of SmtpClient, it’ll
automatically populate with properties mentioned in web.config):
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="<from email
address>">
<network host="smtp.gmail.com" port="587" enableSsl="true" password="<gmail
password>" userName="<gmail user email address>"/>
</smtp>
</mailSettings>
</system.net>
|
Testing the Email: Run the application to send the
test email.
Email Send to Recipient |
Email in Inbox |
You can
also download the working sample of this article.
Comments
Post a Comment