Tuesday, February 14, 2012

Fetch and Read emails from POP3 mail server using C# and VB.Net

In this article 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.
Though the attached sample code has the OpenPop.DLL, still for reference you can download this library from the following URL
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" runat="server" />
<br />
UserName:
<asp:TextBox ID="txtUserName" runat="server" />
<br />
Password:
<asp:TextBox ID="txtPassword" runat="server" TextMode = "Password" />
<br />
Port:
<asp:TextBox ID="txtPort" runat="server" Text = "110" />
<br />
SSL:
<asp:CheckBox ID="chkSSL" 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>
Above you will notice that I have added the Textboxes for various parameters like Mail Server, Username, Password, Port Number of the mail server and a checkbox to allow users define whether the mail server requires SSL or not.
I have also placed an ASP.Net GridView control which will display the emails in tabular format to the users. I have added an asp:HyperLinkField for the Message Subject so that when it is clicked the complete message is displayed to the user.
Namespaces
C#
using OpenPop.Pop3;
using OpenPop.Mime;
using System.Data;

VB.Net
Imports OpenPop.Pop3
Imports OpenPop.Mime
Imports System.Data
Fetching and Reading list of emails from server
On the click of the button btnReadEmails we will execute the event Read_Emails which will fetch and read emails from the POP3 server.
C#
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]["Subject"] = message.Headers.Subject;
        dtMessages.Rows[dtMessages.Rows.Count - 1]["DateSent"] = message.Headers.DateSent;
        counter++;
        if (counter > 5)
        {
            break;
        }
    }
    gvEmails.DataSource = dtMessages;
    gvEmails.DataBind();
}

VB.Net
Protected Sub Read_Emails(ByVal sender As Object, ByVal e As EventArgs)
        Dim pop3Client As Pop3Client
        If (Session("Pop3Client") Is Nothing) Then
            pop3Client = New Pop3Client
            pop3Client.Connect(txtMailServer.Text, Integer.Parse(txtPort.Text), chkSSL.Checked)
            pop3Client.Authenticate(txtUserName.Text, txtPassword.Text)
            Session("Pop3Client") = pop3Client
        Else
            pop3Client = CType(Session("Pop3Client"), Pop3Client)
        End If
        Dim count As Integer = pop3Client.GetMessageCount
        Dim dtMessages As DataTable = New DataTable
        dtMessages.Columns.Add("MessageNumber")
        dtMessages.Columns.Add("From")
        dtMessages.Columns.Add("Subject")
        dtMessages.Columns.Add("DateSent")
        Dim counter As Integer = 0
        Dim i As Integer = count
        Do While (i >= 1)
            Dim message As 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
            counter = counter + 1
            i = i - 1
            If counter = 5 Then
                Exit Do
            End If
        Loop
        gvEmails.DataSource = dtMessages
        gvEmails.DataBind()
End Sub
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
With this we come to the end of this article. This article also has a second part where I will explain how to read and fetch the body of email. The complete code will be available in the Part II of this article series.

Fetch and Read emails from POP3 mail server using C# and VB.Net – Part II  >>


for futher detail: and download this all code please visit:
http://aspsnippets.com/Articles/Fetch-and-Read-emails-from-POP3-mail-server-using-C-and-VB.Net---Part-I.aspx

No comments:

Post a Comment