Reading GMAIL Inbox using ASP.NET - Blogs
X
21Jun

Reading GMAIL Inbox using ASP.NET

In this blog I will explain how to read emails from pop3 server using the free open source library OpenPop.Net. This library provides you very easy API to access and read emails from the POP3 Servers.

Download the library from the following URL.

Download OpenPop.Net

Once you have the library we can start building our sample application that will access and read emails from the POP3 servers. You will need to add the reference of the OpenPop.DLL to your project using Add Reference option in Visual Studio

HTML Markup

<form id="form1" runat="server">
Mail Server Name:
<asp:TextBox ID="txtMailServer"  Text="pop.gmail.com" runat="server" />
<br />
Email ID:
<asp:TextBox ID="txtEmail" runat="server" />
<br />
Password:
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password" />
<br />
Port:
<asp:TextBox ID="txtPort" runat="server" Text="995" />
<br />
SSL:
<asp:CheckBox ID="chkSSL" checked="true" runat="server" />
<br />
<asp:Button ID="btnReadEmails" runat="server" Text="Read Emails" OnClick = "Read_Emails" />
<br /><hr />
<asp:GridView ID="gvEmails" runat="server" AutoGenerateColumns="false">
<Columns>
    <asp:BoundField HeaderText = "From" DataField = "From" />
    <asp:HyperLinkField HeaderText = "Subject" DataNavigateUrlFields = "MessageNumber" 
           DataNavigateUrlFormatString ="~/ShowMessageCS.aspx?MessageNumber={0}" 
           DataTextField = "Subject" />
    <asp:BoundField HeaderText = "Date" DataField = "DateSent" />
Columns>
asp:GridView>
form>
 
 
I have also placed an ASP.Net GridView control which will display the emails in tabular format to the users. I have added anasp:HyperLinkField for the Message Subject so that when it is clicked the complete message is displayed to the user.
 
Namespaces
 
using OpenPop.Pop3;
using OpenPop.Mime;
using System.Data;
 
Fetching and Reading list of emails from server
 
protected void Read_Emails(object sender, EventArgs e)
{
    Pop3Client pop3Client;
    if (Session["Pop3Client"] == null)
    {
        pop3Client = new Pop3Client();
        pop3Client.Connect(txtMailServer.Text, int.Parse(txtPort.Text), chkSSL.Checked);
        pop3Client.Authenticate(txtUserName.Text, txtPassword.Text);
        Session["Pop3Client"] = pop3Client;
    }
    else
    {
        pop3Client = (Pop3Client)Session["Pop3Client"];
    }
    int count = pop3Client.GetMessageCount();
    DataTable dtMessages = new DataTable();
    dtMessages.Columns.Add("MessageNumber");
    dtMessages.Columns.Add("From");
    dtMessages.Columns.Add("Subject");
    dtMessages.Columns.Add("DateSent");
    int counter = 0;
    for (int i = count; i >=1 ; i--)
    {
        Message message = pop3Client.GetMessage(i);
        dtMessages.Rows.Add();
        dtMessages.Rows[dtMessages.Rows.Count - 1]["MessageNumber"] = i;
                dtMessages.Rows[dtMessages.Rows.Count - 1]["From"] = message.Headers.From.Address;
        dtMessages.Rows[dtMessages.Rows.Count - 1]["Subject"] = message.Headers.Subject;
        dtMessages.Rows[dtMessages.Rows.Count - 1]["DateSent"] = message.Headers.DateSent.ToLocalTime();
        counter++;
        if (counter > 4)
        {
            break;
        }
    }
    gvEmails.DataSource = dtMessages;
    gvEmails.DataBind();
}
 
On the click of the button btnReadEmails we will execute the event Read_Emails which will fetch and read emails from the POP3 server.
In the above code snippet I am using the Pop3Client class OpenPop.Net Library to connect to the POP3 server and fetching the emails. Below are the steps that describes how the library works
1. The client connects to the POP3 server using the server URL and Port Number
2. The client authenticates the user based on username and password.
3. The client fetches the total count of the messages on the server.
4. Based on the count we run a loop and start fetching the emails from the server.
Note: Since fetching emails is a time consuming process I am fetching only latest 5 emails from the server. You can later on remove that condition as per your requirement
Screenshot
Read and fetch emails from pop3 server using c#
In the GridView I made the Subject field of the Email as Hyperlink and which when clicked redirects the user to another page named ShowMessage.aspx which as the named suggests displays the complete email.
HTML Markup
Below is the HTML Markup of the ShowMessage.aspx page
<form id="form1" runat="server">
<div>
From: <asp:Label ID="lblFrom" runat="server" Text="" />
<br />
Subject: <asp:Label ID="lblSubject" runat="server" Text="" />
<br />
Body: <asp:Label ID="lblBody" runat="server" Text="" />
div>
form>
As you will notice the page is quite simple it has three labels to display
1. From Email
2. Subject of the email
3. Body of the email

Fetch and Display the message
From the main page I pass the MessageNumber as parameter via QueryString to the ShowMessage page. Here based on the MessageNumber I am fetching the complete message using the following code snippet.
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Pop3Client pop3Client = (Pop3Client)Session["Pop3Client"];
        int messageNumber = int.Parse(Request.QueryString["MessageNumber"]);
        Message message = pop3Client.GetMessage(messageNumber);
        MessagePart messagePart = message.MessagePart.MessageParts[0];
        lblFrom.Text = message.Headers.From.Address;
        lblSubject.Text = message.Headers.Subject;
        lblBody.Text = messagePart.BodyEncoding.GetString(messagePart.Body);
    }
}
Screenshot
Read and fetch emails from pop3 server using c#

THANK YOU

Related

What are Frames? How to handle frames in Selenium WebDriver with C#?

IFrame (FullForm: Inline Frame) is an HTML document that is included in another HTML document and is...

Read More >

What is Synchronization? Handling Synchronization in Selenium WebDriver using C#:

Synchronization meaning: when two or more components involved to perform any action, we expect these...

Read More >

Sending Test reports by Email using Office 365, Gmail

Wouldn’t it be great if Test Report are sent automatically across team as soon the Test Execut...

Read More >

ASP.NET: Audit Trail Implementation using Entity Framework

When you are working with certain projects which involves the Customer records, you might need to tr...

Read More >

Create Restful service using Web API

What is Asp.Net Web API?Asp.Net Web API is a framework for building HTTP services that can be consum...

Read More >

Create custom project templates in Visual Studio

Visual studio installation comes with the various predefined project templates, and we can use one o...

Read More >

WCF SOAP and REST Services

WCF (Windows Communication Foundation) is a programming platform and runtime system for building, co...

Read More >

What's New In C# 6.0?

Microsoft has released the preview version of Visual Studio 2015 and .NET 4.6 for developers to try ...

Read More >

Creating an RDLC report in Asp.Net

Step 1.  Create a new website and Add DataSet to the WebsiteRight Click on the project, Add new...

Read More >

How to add Overlay in Windows phone 8

Windows Phone is windows mobile operating system from Microsoft.In my project, there was a requireme...

Read More >

Share

Try DevOpSmartBoard Ultimate complete Azure DevOps End-to end reporting tool

Sign Up

  • Recent
  • Popular
  • Tag
Tags
Monthly Archive
Subscribe
Name

Text/HTML
Contact Us
  • *
  • *