Skip to main content

How to Send email in ASP.Net and C# using Gmail SMTP Server

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

Popular posts from this blog

C#: Merging Excel cells with NPOI HSSFWorkbook

In this post we’ll see how to merge the two or more cell with each other while creating the excel sheet using NPOI . Mentioned below is code to merge multiple cells, in this example we are merging first cell to fifth cell of first row (you can adjust row or cell range by passing particular parameters in CellRangeAddress). //Created new Workbook var hwb = new NPOI.HSSF.UserModel. HSSFWorkbook (); //Create worksheet with name. var sheet = hwb.CreateSheet( "new sheet" ); //Create row and cell. var row = sheet.CreateRow(0); var cell = row.CreateCell(0); ; //Set text inside cell cell.SetCellValue( "This is Merged cell" ); cell.CellStyle.WrapText = true ; //define cell range address // parameters: -> first row to last and first cell to last cell var cra = new NPOI.SS.Util. CellRangeAddress (0, 0, 0, 4); //Add merged region to sheet. sheet.AddMergedRegion(cra); Hope this solution helps you J

Difference between Web API, WCF and Web Service

So now we have got the basic idea about Web API , now let’s do some comparison of Web API with WCF and web services. Web Service WCF Web API Web services are created as files with .asmx extension. WCF create with .svc extension Web API are simple class file with .cs(for C#) extension. Web API is inherited from “ApiController” and the class name must end with “Controller”. It is SOAP based service and returns data in XML form. It is also based on SOAP and returns data in XML form. Web API is HTTP based service and by default, it returns data in JSON or XML form. It supports only HTTP protocol. It supports various protocols like TCP, HTTP, HTTPS, Named Pipes, and MSMQ. It supports HTTP protocol. It can be hosted only on IIS. It can be hosted within the application or on IIS or using window service. It can be hosted within the application or on IIS. It is no...