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

Error 405 : ASP.NET Core Web API PUT and DELETE Methods not allowed

Recently, while working with .Net core API I came across the issue of “Error 405 — Methods not Allowed” After some research, I found out that both GET and POST requests working fine but neither PUT nor DELETE requests working. Another thing is that the PUT and DELETE request was also working fine on my local machine but failed when we host on our Azure server. When I explored the issue on the web it led me to the conclusion that WebDAVModule seems to set PUT and DELETE request methods disabled by default and due to that PUT and DELETE throw 405 errors. To make the PUT and DELETE requests work, we need to override the WebDAVModule setting in web.config file by adding the below settings under “ system.webServer ”. < system.webServer >   < modules runAllManagedModulesForAllRequests = " false " >     < remove name = " WebDAVModule " />   </ modules > </ system.webServer > There may be 2 web.config files in y...

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

How to set Swagger as the default start page for API hosted on the Azure web app?

I created an Asp.Net Core 2.x Web API and configured Swagger on it, below is the code added in Configure method under Startup.cs file, for full swagger configuration, check here //Add swagger configuration app.UseSwagger(); app.UseSwaggerUI(c => {     c.SwaggerEndpoint( "../swagger/v1/swagger.json" , "Test API V1" ); }); On my local machine when I run the API it is automatically redirected to the Swagger page. However, when I hosted this API as an Azure web app it is not redirecting directly to the Swagger and to access the swagger, I had to append /swagger in the URL, for example, https://testapi.azurewebsites.net/swagger/ Solution: Set RoutePrefix to string.Empty under app.UseSwaggerUI like below: app.UseSwaggerUI(c => {     c.SwaggerEndpoint( "../swagger/v1/swagger.json" , "Test API V1" );      c.RoutePrefix = string .Empty; // Set Swagger UI at apps root }); And that’s it, now when you b...