AspnetO

We code, that works!

  • Home
  • Asp.net
  • MVC
  • Interview Questions

How to Send Test Mail using Gmail smtp Settings in Asp.net C# Vb.net?

By: Mayank Modi | Folls In: Asp.net, C#, VB | Last Updated: Aug 26, 2014

In my previous tutorials, I’d explained how to send asp.net gridview in mail, how to send HTML web page as email and more cracking tutorials on Repeater, Gridivew, Asp.net, JavaScript, jQuery here.

Now here in this tutorial, I’ll explain how to send test mail using Gmail smtp settings in asp.net using c# and vb.net.

The .NET framework has built-in namespace for handling email settings, which is System.Net.Mail namespace. In the following example, I’ll use two classes from the System.Net.Mail namespace:

  • For email settings, we will use the MailMessage class and
  • For smtp settings and sending email, we will use the SmtpClient class

I guess you are aware that mails are sent via an SMTP server, so we need to integrate smtp settings such as SMTP Host, Port, Credentials etc. If you don’t know about such things don’t worry, I’ll cover all these things in this tutorial.

What is SMTP?

SMTP stands for Simple Mail Transfer Protocol. It provides set of communication settings that allows our software or web applications to transmit or send emails over the internet with configured smtp settings.

Required Gmail SMTP Settings

Following are the list of SMTP settings that are mainly required to send emails:

  • SMTP Server/Host: It’s a server name. For example, smtp.gmail.com
  • SMTP Username: Your full email address. For example, [email protected]
  • SMTP Password: Your account password
  • SMTP port (TLS): 587
  • SMTP port (SSL): 465
  • SMTP TLS/SSL required: yes
Note: If you have your own email provider and you want to use that details then you can use that too.

Now we have all required details available, so we can go ahead and implement code.

HTML Markup Code To Send Mail – [.aspx]

Following is the complete HTML markup code for .aspx page shown as below:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
       <title>Send test mail using smtp settings in asp.net</title>
</head>
<body>
       <form id="form1" runat="server">
       <div>
       <table>
               <tr>
                       <td>
                               <h4>Send test mail using smtp settings in asp.net</h4>
                       </td>
               </tr>
               <tr>
                       <td>
                               <asp:TextBox ID="txtToEmail" runat="server" Width="250" Height="28"
                               placeholder="To email: [email protected]"></asp:TextBox>
                               <asp:RequiredFieldValidator ID="rfvToEmail" runat="server" ForeColor="Red"
                               ControlToValidate="txtToEmail" ErrorMessage="Required" Display="Dynamic">
                               </asp:RequiredFieldValidator>
                               <asp:RegularExpressionValidator ID="revToEmail" runat="server"
                               ControlToValidate="txtToEmail" ForeColor="Red" ErrorMessage="Invalid Email"
                               ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
                               </asp:RegularExpressionValidator>
                       </td>
               </tr>
               <tr>
                       <td>&nbsp;&nbsp;</td>
               </tr>
               <tr>
                       <td>
                               <asp:TextBox ID="txtMessage" runat="server" placeholder="Your body message"
                               Width="250" Height="150" TextMode="MultiLine"></asp:TextBox>
                               <asp:RequiredFieldValidator ID="rfvMessage" runat="server"
                               ControlToValidate="txtMessage" ForeColor="Red" ErrorMessage="Required">
                               </asp:RequiredFieldValidator>
                       </td>
               </tr>
               <tr>
                       <td>&nbsp;&nbsp;</td>
               </tr>
               <tr>
                       <td>
                               <asp:Button ID="btnSend" runat="server" Text="Send Mail!" OnClick="btnSend_Click" />
                       </td>
               </tr>
               <tr>
                       <td>&nbsp;&nbsp;</td>
               </tr>
               <tr>
                       <td>
                               <asp:Label ID="lblMsg" runat="server"></asp:Label>
                       </td>
               </tr>
       </table>
       </div>
       </form>
</body>
</html>

Following is the code that we need to use for sending emails, choose your language from below.

Send Mail Using Gmail Settings Sample Code – [C#]

Add the following namespace that is required for sending emails:

using System.Net.Mail;

Now following is the code that we can use to send emails using MailMessage class:

protected void Page_Load(object sender, EventArgs e)
{
}

protected void btnSend_Click(object sender, EventArgs e)
{
       try
       {
               string Subject = "This is test mail using smtp settings",
               Body = txtMessage.Text.Trim(),
               ToEmail = txtToEmail.Text.Trim();

               string SMTPUser = "[email protected]", SMTPPassword = "yourpassword";

               //Now instantiate a new instance of MailMessage
               MailMessage mail = new MailMessage();

               //set the sender address of the mail message
               mail.From = new MailAddress(SMTPUser, "AspnetO");

               //set the recepient addresses of the mail message
               mail.To.Add(ToEmail);

               //set the subject of the mail message
               mail.Subject = Subject;

               //set the body of the mail message
               mail.Body = Body;

               //leave as it is even if you are not sending HTML message
               mail.IsBodyHtml = true;

               //set the priority of the mail message to normal
               mail.Priority = MailPriority.Normal;

               //instantiate a new instance of SmtpClient
               SmtpClient smtp = new SmtpClient();

               //if you are using your smtp server, then change your host like "smtp.yourdomain.com"
               smtp.Host = "smtp.gmail.com";

               //chnage your port for your host
               smtp.Port = 25; //or you can also use port# 587

               //provide smtp credentials to authenticate to your account
               smtp.Credentials = new System.Net.NetworkCredential(SMTPUser, SMTPPassword);

               //if you are using secure authentication using SSL/TLS then "true" else "false"
               smtp.EnableSsl = true;

               smtp.Send(mail);

               lblMsg.Text = "Success: Mail sent successfully!";
               lblMsg.ForeColor = System.Drawing.Color.Green;
       }
       catch (SmtpException ex)
       {
               //catched smtp exception
               lblMsg.Text = "SMTP Exception: " + ex.Message.ToString();
               lblMsg.ForeColor = System.Drawing.Color.Red;
       }
       catch (Exception ex)
       {
               lblMsg.Text = "Error: " + ex.Message.ToString();
               lblMsg.ForeColor = System.Drawing.Color.Red;
       }
}

Send Mail Using Gmail Settings Sample Code – [Vb.net]

Add the following namespace that is required for sending emails:

Imports System.Net.Mail

Now following is the code that we can use to send emails using MailMessage class:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub

Protected Sub btnSend_Click(ByVal sender As Object, ByVal e As EventArgs)
       Try
               Dim Subject As String = "This is test mail using smtp settings",
               Body As String = txtMessage.Text.Trim(), ToEmail As String = txtToEmail.Text.Trim()

               Dim SMTPUser As String = "[email protected]",
               SMTPPassword As String = "yourpassword"

               'Now instantiate a new instance of MailMessage
               Dim mail As New MailMessage()

               'set the sender address of the mail message
               mail.From = New MailAddress(SMTPUser, "AspnetO")

               'set the recepient addresses of the mail message
               mail.To.Add(ToEmail)

               'set the subject of the mail message
               mail.Subject = Subject

               'set the body of the mail message
               mail.Body = Body

               'leave as it is even if you are not sending HTML message
               mail.IsBodyHtml = True

               'set the priority of the mail message to normal
               mail.Priority = MailPriority.Normal

               'instantiate a new instance of SmtpClient
               Dim smtp As New SmtpClient()

               'if you are using your smtp server, then change your host like "smtp.yourdomain.com"
               smtp.Host = "smtp.gmail.com"

               'chnage your port for your host
               smtp.Port = 25 'or you can also use port# 587

               'provide smtp credentials to authenticate to your account
               smtp.Credentials = New System.Net.NetworkCredential(SMTPUser, SMTPPassword)

               'if you are using secure authentication using SSL/TLS then "true" else "false"
               smtp.EnableSsl = True

               smtp.Send(mail)

               lblMsg.Text = "Success: Mail sent successfully!"
               lblMsg.ForeColor = System.Drawing.Color.Green
       Catch ex As SmtpException
               'catched smtp exception
               lblMsg.Text = "SMTP Exception: " & ex.Message.ToString()
               lblMsg.ForeColor = System.Drawing.Color.Red
       Catch ex As Exception
               lblMsg.Text = "Error: " & ex.Message.ToString()
               lblMsg.ForeColor = System.Drawing.Color.Red
       End Try
End Sub

Example Result

How to send test mail using gmail smtp settings in asp.net c# vb.net

Download Example

Icon
SMTP Email Sending Examples 43.07 KB
Download This Example

Signup Today And Get Latest Tutorials For Free!

Subscribe to us and get free latest tutorials notifications whenever we publish a new contents.

About Mayank Modi

Mayank is a web developer and designer who specializes in back-end as well as front-end development. He's a Founder & Chief Editor of AspnetO. If you'd like to connect with him, follow him on Twitter as @immayankmodi.

Comments

  1. Sanjay Kumar Yadav says

    Jun 01, 2018 at 9:07 AM

    Very good post thank you so much

    Reply
  2. Prasad Joshi says

    Oct 03, 2016 at 5:52 PM

    Dear Mayank,

    Hi, i am .Net Developer. the current task i have is i need to read the unread mail from my gmail inbox.

    i am able to read all mail present in the inbox but i need to filter with only unread mail.

    Appreciate your support

    Thanks and Regards

    Prasad Joshi

    Reply

Share Your Comments & Feedback Cancel reply

Note: To post any code in comment, use <pre>your code</pre>

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Social Connections

  • 0 Fans
  • 3,360 Followers
  • 21 Followers
  • 49 Followers
  • 1,559 Subscribers

Top Posts

  • CSS3 Transition: fadeIn and fadeOut like Effects to Hide Show Elements
  • Tooltip: Show Hide Hint Help Text Example in CSS3 Transition
  • Parser Error While Deploying Website to Server in Asp.net
  • How to split string into Array of Day, Month, Year in Asp.net Using C# Vb.net
  • Get Selected Text Value from DropDownList in Asp.net using JavaScript

Find by Tags

Ado.net Ajax appSettings Asp.net C# CheckBox CheckBoxList ConnectionStrings Control CSS CSS3 Difference Download DropDownList Export Facebook fadeIn fadeOut fadeTo fadeToggle File File Extension FileUpload Function GridView IIS Interview Questions JavaScript jQuery MVC OOP RadioButtonList RDP Repeater Send Mail Solutions Split SQL Stored Procedure TextBox Upload Validation VB Web.config Web Hosting

The Man Behind AspnetO

Mayank Modi

Hi there,

Myself Mayank Modi, a Software Engineer and a blogger from Surat, India.

I'm welcoming you to my blog - AspnetO, a programmers community blog where we code, that works!

I started AspnetO as a hobby and now we're growing day by day. We're now having 2500+ programmers that get benefits and learn new things about website design and development under our community blog.

Here at AspnetO, I write about Beginners to Advance level of tutorials on programming languages like Asp.net using C# and Vb.net, MVC, SQL Server, JavaScript, jQuery etc. In sort, all about Asp.net website development stuff and sometimes sharing tips and tricks that can help you to grow up your programming skills.

You can get more details about me and my blog at About us page.

Subscribe To Newsletter

Enter your email address to subscribe to this blog and receive notifications of new posts right to your inbox

Join 1000+ other subscribers

Alexa Traffic Rank

Hot on AspnetO

Icon
Gridview Insert Update Delete Example in Asp.net, C#, Vb.net 7036 downloads 39.76 KB
Download This Example
Icon
Gridview Insert Update Delete Example in Asp.net, C#, Vb.net 6067 downloads 39.76 KB
Download This Example
Icon
Gridview Insert Update Delete Example in Asp.net, C#, Vb.net 6061 downloads 39.76 KB
Download This Example
Icon
Export gridview all rows or selected rows to word, excel, text, pdf examples 2883 downloads 1.01 MB
Download This Example
Icon
Export gridview all rows or selected rows to word, excel, text, pdf examples 2852 downloads 1.01 MB
Download This Example

Copyright © 2014 - 2019 · All Rights Reserved.

About | Copyrights | Privacy | Terms | Contact | Advertise | Sitemap
Previous Top 10 OOPS Concepts In C# .NET With Examples
Next Send Asp.net GridView Data in smtp Mail in Asp.net C# Vb.net