ASP.Net IMAP Email Checker

Posted: 10/09/2006 17:22:17
Author: Andy Pilgrim
Is ASP.Net 1.x Compatible? Yes! ASP.Net 1.x Compatible (?)

    IMAP is an alternative to POP3 mail retrieval. IMAP has several advantages over POP3, not least that it allows email to be stored permanently on the server so that it can be accessed from anywhere. For this reason, I choose to collect my mail via IMAP. Recently, I wanted to build a small ASP.Net email checker component which connected to the server got the unread count, and displayed it on page. The problem with IMAP over POP3 is that its extra features make it more complex. It soon became clear that ASP.Net code to retrieve POP3 email is widely available, however, few examples of IMAP mail retrieval exist.

    Lumisoft IMAP Component

    Rather than write the code for the IMAP communication manually, the Lumisoft IMAP component gives us everything we need, furthermore, its freeware! The IMAP component allows us to connect to IMAP servers to retrieve messages and also do simple stuff like get the unread message count. You can download the component here.

    Building an ASP.Net Email Checker User Control

    User controls are a simple way to include chunks of UI and code into pages. For this article we’ll build a user control that displays the new message count as shown below:

    Email Checker Sample
    Icons by Mark James

    The first step is to create a .ascx file. Using Visual Web Developer Express you can opt to create a new user control and you get the following template:

    <%@ Control Language="VB" ClassName="WebUserControl" %>
    <script runat="server">
    
    </script>

    .ascx files essentially function like fragments of a full ASP.Net page. So they have the script tag in which you can specify the usual events such as Page_Load(), and the rest of the page in which you specify HTML mark up. In addition to the events in the script tags, you can also specify properties, which we’ll come back to later.

    As for the mark up, we’ll use a few labels and an ASP.Net image control:

    <div class="mailnotification">
        <asp:Label ID="notificationtitle" runat="server" />: 
        <span runat="server" id="notificationoutput">
            <asp:image ID="notificationicon" runat="server" /> 
            <asp:Label ID="notificationtext" runat="server" />
        </span>     
    </div>

    The span and div tags are just there to make assigning CSS classes easier. So the notificationtitle will give the mailbox name and the notificationtext label outputs the unread count. The notificationicon image control will just be a pretty graphic.

    In the script tags we’ll now specify some properties which will allow us to define which mailbox to check:

    Dim _Username As String
    Dim _Password As String
    Dim _MailServer As String
        
    Public Property Username() As String
        Get
            Return _Username
        End Get
        Set(ByVal value As String)
            _Username = value
            notificationtitle.Text = value
        End Set
    End Property
     
    Public Property Password() As String
        Get
            Return _Password
        End Get
        Set(ByVal value As String)
            _Password = value
        End Set
    End Property
       
    Public Property MailServer() As String
        Get
            Return _MailServer
        End Get
        Set(ByVal value As String)
            _MailServer = value
        End Set
    End Property

    So we’ve got the properties Username, Password and Mailserver, their internal representations having an underscore in front. These properties are accessible from the ASP.Net page in which we include the control (more on this later).

    We need to include a reference to the IMAP control at the top of the page. This is done using the Import directive as shown below. We must also include the component in the bin folder of the application.

    <%@ Import Namespace="LumiSoft.Net.IMAP" %>
    <%@ Import Namespace="LumiSoft.Net.IMAP.Client" %>
    

    Then we do the actual mail server stuff:

    Protected Sub Page_Load()
      If Not Page.IsPostBack Then
        Dim IMAPServer As IMAP_Client = New IMAP_Client
        Try
          IMAPServer.Connect(_MailServer, 143)
          IMAPServer.Authenticate(_Username, _Password)
          IMAPServer.SelectFolder("INBOX")
          If IMAPServer.GetUnseenMessagesCount = 0 Then
            notificationicon.ImageUrl = "~/images/emailfalse.png"
          Else
            notificationicon.ImageUrl = "~/images/unread.png"
          End If
          If IMAPServer.GetUnseenMessagesCount = 1 Then
            notificationtext.Text = "1 new message"
          Else
            notificationtext.Text = _ 
                IMAPServer.GetUnseenMessagesCount & " new messages"
          End If
        Catch ex As Exception
          notificationicon.Visible = False
          notificationtext.Text = "Error getting message count"
          notificationtitle.Attributes.Add("title", ex.Message)
        Finally
          IMAPServer.Disconnect()
        End Try
      End If
    End Sub

    We handle the page_load() event. First we check whether the page is being called for real and its not just a postback. There is no need to check the count again on postback. We then create a IMAP_Client object. Enclosing the whole lot in a try block we connect to the server and login using the supplied properties. Then we select the INBOX folder from the IMAP server and use IMAPServer.GetUnseenMessagesCount to retrieve the unread messages count. The remaining if statements sort out the grammar and setting the correct image to display. Finally, we disconnect from the server.

    That is all the user control done. To use it on an ASP.Net page, use the following:

    <%@ Page Language="VB" %>
    <%@ Register Src="EmailSummary.ascx" 
        TagName="EmailSummary" TagPrefix="ap" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <script runat="server">
    
    </script>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
      <title>Untitled Page</title>
    </head>
    <body>
      <form id="form1" runat="server">
      <div>
        <ap:EmailSummary username="user@domain.com" 
          password="password"
          mailserver="imap.domain.com"
          runat="server" />    
      </div>
      </form>
    </body>
    </html>

    The Register directive at the top of the page tells ASP.Net we’re using the user control and where to find it. We then can insert the control using <ap:EmailSummary /> tag. In this tag we specify the attributes Username, Password and MailServer which correspond to the properties we defined in .ascx file.

    The code can be downloaded from http://download.semichaos.com/emailchecker.zip