Access Outlook Emails with ASP.NET, C#

Posted: January 16, 2008 in ASP.NET
Tags: , ,

To access outlook emails and its contents like total number of emails in inbox, number of unread emails, subject and title of email, attachments of email etc. To acquire these, all you need is Interop.Outlook.dll. How to access outlook using ASP.NET is given below. You can write this code in a button click event or in page load event. The code part contains C# language:

 

 using Outlook;

 Outlook.Application oOutlook;
 Outlook.NameSpace oNs;
 Outlook.MAPIFolder oFldr;
 long iAttachCnt;

 try
 {
     oOutlook = new Outlook.Application();
     oNs = oOutlook.GetNamespace(“MAPI”);

     //getting mail folder from inbox
     oFldr = oNs.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
     Response.Write(“Total Mail(s) in Inbox :” + oFldr.Items.Count + “<br>”);
     Response.Write(“Total Unread items = ” + oFldr.UnReadItemCount);
     foreach (Outlook.MailItem oMessage in oFldr.Items)
     {
         StringBuilder str = new StringBuilder();
         str.Append(“<table style=’border:1px solid gray;font-family:Arial;font-size:x-small;width:80%;’ align=’center’><tr><td style=’width:20%;’><b>Sender :</b></td><td>”);
         str.Append(oMessage.SenderEmailAddress.ToString() + “</td></tr>”);
         //basic info about message
         str.Append(“<tr><td><b>Date :</b></td><td>” + oMessage.SentOn.ToShortDateString() + “</td></tr>”);
         if (oMessage.Subject != null)
         {
             str.Append(“<tr><td><b>Subject :</b></td><td>” + oMessage.Subject.ToString() + “</td></tr>”);
         }
         //reference and save all attachments

         iAttachCnt = oMessage.Attachments.Count;
         if (iAttachCnt > 0)
         {
             for (int i = 1; i <= iAttachCnt; i++)
             {
                 str.Append(“<tr><td><b>Attachment(” + i.ToString() + “) :</b></td><td>” + oMessage.Attachments[i].FileName + “</td></tr>”);
             }
         }
         str.Append(“</table><br>”);
         Response.Write(str.ToString());

     }

 }
 catch (System.Exception ex)
 {
     Response.Write(“Execption generated:” + ex.Message);
 }
 finally
 {
     GC.Collect();
     oFldr = null;
     oNs = null;
     oOutlook = null;

 }

Advertisements
Comments
  1. Raghu Veer Gupta says:

    I applied your code in my project, but still i am getting error saying that “Execption generated:Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046} failed due to the following error: 80080005.”

    Help me in this matter. I would be very thankful if anyone provide solution

  2. hspinfo says:

    Hi Raghu,

    I guess, you must be using “Outlook Express” instead of “Microsoft Office Outlook”. If true then you need to install MS Outlook and try with the code.

  3. This error is not because of Outlook Express or Microsoft Outlook.

    While iterating the emails, there are some mails that are not of the type MailItem, which throw this error.

    You can skip such items from the list.

  4. Saqib Razzaq says:

    An easy alternate would be to choose some 3rd party component that supports parsing outlook message (.msg) files. Check out http://www.aspose.com/documentation/utility-components/aspose.network-for-.net/loadingviewingparsing-outlook-message-msg-file.html for an article how to read the contents of an msg file.

  5. Sudhakar says:

    Use this code to access only mail items.

    Outlook.MAPIFolder oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
    Outlook.Items oItems = oInbox.Items;
    oItems=oItems.Restrict(“[Messageclass]=’IPM.Note'”);

  6. Sanjay Minhas says:

    Hi Thanks !

    but getting this error after reading few mails.

    Please advise …..!

    Execption generated:Unable to cast COM object of type ‘System.__ComObject’ to interface type ‘Microsoft.Office.Interop.Outlook.MailItem’. This operation failed because the QueryInterface call on the COM component for the interface with IID ‘{00063034-0000-0000-C000-000000000046}’ failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).

  7. Ajit says:

    this sounds like a too many RPC connections problem.

    in an Exchange evnvironment by default one PC can have no more then 250 open RPC connections.

    I added a garbage collection line to the code that executes every 100 iterations and it runs all the way through! This is the bit that I added.

    Code Snippet
    ‘this line was added outside the loop

    Dim garbage As Decimal = 0

    ‘these were inside the loop

    garbage = i / 100

    If garbage = Math.Round(garbage) Then

    Try

    GC.Collect()

    Console.WriteLine(“Garbage collection complete.”)

    Catch ex As Exception

    Console.WriteLine(“Garbage collection FAILED! Program terminated.”)

    Exit Sub

    End Try

    End If

  8. ankita says:

    Hi
    I am receiving an error “couldnt star ms office outlook. MAPI32.dll is corrupted or wrong version”. Please tell me what is the problem. Please help and reply ASAP

    thanks

  9. Rahul says:

    Hi,

    I need to reply to a particular email. Please guise how should I using the above code?

    thanks

  10. Quest says:

    Hi,

    I want to know how to read the subject of the e-mail in the InBox using Outlook API (programatically)

    Also, I want to know how to achieve the following things programatically.

    – Marking the Read e-mails as Read.
    – Moving the e-mails to specific folders.

  11. Microsroft Office is still the best program when it comes to spreadsheet and word processing-‘~

  12. i use both open office and microsoft office and i would say that microsoft office is more responsive and user friendly ;”`

  13. Rakesh says:

    hi,
    this code does not read my inbox.
    I got an error ” ‘inboxFld.InAppFolderSyncObject’ threw an exception of type ‘System.Runtime.InteropServices.COMException'”

  14. yogesh says:

    i am getting error like ‘outlook does not exist’
    i am using namespace’using outlook’

    ps reply utgent.

    thanks

  15. Tassisto says:

    Is this problem solved? I can’t see a solution???

  16. biraj says:

    This is really helpful.

    ThANKS MAN.

  17. rahul says:

    thanx bro..

  18. sanjubaba says:

    Hi all,

    iam getting this error and i have also tried Ajit’s soluotion but still getting the same error..

    Any Solution??

    Any help will be highly appreciated..

    thanks

    Execption generated:Unable to cast COM object of type ‘System.__ComObject’ to interface type ‘Microsoft.Office.Interop.Outlook.MailItem’. This operation failed because the QueryInterface call on the COM component for the interface with IID ‘{00063034-0000-0000-C000-000000000046}’ failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s