Tim Huffam

Dotting the I and crossing the T of I.T.

  Home  |   Contact  |   Syndication    |   Login
  153 Posts | 0 Stories | 2747 Comments | 653 Trackbacks

News

Archives

Post Categories

Interesting Blogs/Links

The following demostrates how to retreive data from items within an Outlook folder (called "MySubFolderName" under the Inbox folder) using .NET:

First add a reference to the Outlook COM object your project:

  1. In VS.NET right click on References and choose Add Reference.
  2. Select the COM tab
  3. Choose "Microsoft Outlook 11.0 Object Library" (this is for MS Office 2003 - I think 10.0 is for Office XP) and click Select.
  4. Click OK.

Note that you can access any Outlook/Exchange object types, eg Appointments, Notes, Tasks, Emails etc - just use intellisense to select which one (eg Microsoft.Office.Interop.Outlook. ... - see definition of variable called 'item' below).

Here's the code:

Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook._NameSpace ns = null;
Microsoft.Office.Interop.Outlook.PostItem item = null;
Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;
Microsoft.Office.Interop.Outlook.MAPIFolder subFolder = null;

try
{
  app = new Microsoft.Office.Interop.Outlook.Application();
  ns = app.GetNamespace("MAPI");
  ns.Logon(null,null,false, false);

  inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
  subFolder = inboxFolder.Folders["MySubFolderName"]; //folder.Folders[1]; also works
  Console.WriteLine("Folder Name: {0}, EntryId: {1}", subFolder.Name, subFolder.EntryID);
  Console.WriteLine("Num Items: {0}", subFolder.Items.Count.ToString());

  for(int i=1;i<=subFolder.Items.Count;i++)
  {
    item = (Microsoft.Office.Interop.Outlook.PostItem)subFolder.Items[i];
    Console.WriteLine("Item: {0}", i.ToString());
    Console.WriteLine("Subject: {0}", item.Subject);
    Console.WriteLine("Sent: {0} {1}" item.SentOn.ToLongDateString(), item.SentOn.ToLongTimeString());
    Console.WriteLine("Categories: {0}", item.Categories);
    Console.WriteLine("Body: {0}", item.Body);
    Console.WriteLine("HTMLBody: {0}", item.HTMLBody);
  }
}
catch (System.Runtime.InteropServices.COMException ex)
{
  Console.WriteLine(ex.ToString());
}
finally
{
  ns = null;
  app = null;
  inboxFolder = null;
}

HTH

Tim

posted on Friday, May 26, 2006 10:35 AM

Feedback

# re: Accessing Outlook items from C# .NET 5/26/2006 4:00 PM alcsharp
I was looking for exactly this. The only thing I had to change was casting to a MailItem instead of a PostItem in the for loop cuz I was getting an error. Works great.... TY

# re: Accessing Outlook items from C# .NET 5/27/2006 8:40 AM Abdul Kader Jilani
item = (Microsoft.Office.Interop.Outlook.PostItem)subFolder.Items[i];
its giving ...
Unhandled Exception: System.InvalidCastException: Specified cast is not valid.

# re: Accessing Outlook items from C# .NET 5/27/2006 8:43 AM Abdul Kader Jilani
Thanks its working now.

# re: Accessing Outlook items from C# .NET 5/27/2006 10:19 AM Abdul Kader Jilani
its not working in other PC

# re: Accessing Outlook items from C# .NET 5/27/2006 10:20 AM Abdul Kader Jilani
its deployment version is not working in other PC

# re: Accessing Outlook items from C# .NET 9/7/2007 6:01 AM Naveen
can you help how to &quot;Mark an Email as Read&quot;?
That will help me a lot.
I will be very thankful to you on reply.


# re: Accessing Outlook items from C# .NET 10/10/2007 9:47 AM Sebas
I've got a list of 502 items. I can get the first (newest) 240 items. The I cant get them because the items are not postitems or mailitems (or any other item, checked them all) I suspect that there was a migration from exchange 2000 to 2003 arround the date of itemnumber 241. Doe this ring a bell??

Thanks,

Bas

# re: Accessing Outlook items from C# .NET 10/12/2007 4:44 AM Jayanth
I have got 4 attachments it's extensions are .xsn & .lgo. i am able to extract attachments with extension'e .lgo through Microsoft.Office.Interop.Outlook.PostItem. but i can't extract .xsn files. it's giving me error like unable to convert system._comobject. is there any other way to type cast the items? please help me.

# re: Accessing Outlook items from C# .NET 11/26/2007 1:14 PM satish
when i use this (Outlook.PostItem) _item; i am getting error "Specified cast is not valid. "

# re: Accessing Outlook items from C# .NET 12/17/2007 12:38 PM abhishek
hi,

i want to disable "automatic download" feature of MS Outlook 2007 in "trust center" thrugh C#.net.
pls tell me the solution.

# rdisable "automatic download" in C# .NET 12/17/2007 1:30 PM saurabh
hi,

i want to disable "automatic download" feature of MS Outlook 2007 in "trust center" thrugh C#.net.

pls tell me the solution.


Thanks in Advance..

Saurabh..


# re: Accessing Outlook items from C# .NET 1/9/2008 4:22 AM srinivas
hi,


i want to access the SEND button in compose. using c# how can we display a message when send button clicked?

pls tell me the solution


thnks n regards,
Srinivas

# re: Accessing Outlook items from C# .NET 1/10/2008 11:24 PM chris
How to run this code in a deployment scenario? coz as far as i can guess, this runs in the context of the logged in user,so if we are deploying ths code to a server, surely it will fail.
So how to access the mailbox of a user in this scenario?



# re: Accessing Outlook items from C# .NET 2/20/2008 11:34 AM adam
How can we specify which user's mailbox to log on to?

# re: Accessing Outlook items from C# .NET 2/22/2008 12:17 PM Sean
Hi,
I just want to say how utterly fantastic I found this page. This is just what I was looking for also. Perfect!

It will allow me to do custom scaping of my outlook files for certain text and make email lists!!

Cheers to you!

Best - Sean

# re: Accessing Outlook items from C# .NET 4/16/2008 6:06 PM Johnson
Hi,

After the 240 Mail items i can't access the mail items.

Could u help me.....

Thanks.

# re: Accessing Outlook items from C# .NET 5/26/2008 8:12 PM Harry_cherry
Hi ;

My task is to read alll the emails from the outlook component . Here is te code I am using and getting the error :" Specified cast not valid"

Dim _objItem As Outlook.MailItem = Nothing
Dim _objInboxFolder As Outlook.MAPIFolder = Nothing
Dim _objSubfolder As Outlook.MAPIFolder
Dim _outlook As Outlook.MailItemClass
Dim _outlookObj As New Outlook.Application
Dim _outlookNamespace As Outlook.NameSpace
_outlookNamespace = _outlookObj.GetNamespace("MAPI")
_outlookNamespace.Logon(Nothing, Nothing, False, False)
_objInboxFolder = _outlookNamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)
_objSubfolder = _objInboxFolder.Folders(1)
Response.Write("Folder Name: " & _objSubfolder.Name & " Entry ID" & _objSubfolder.EntryID)
Response.Write("Num Items: " & _objSubfolder.Items.Count)
Dim _itemCount As Integer = _objSubfolder.Items.Count
While (_itemCount <> 0)
_objItem = CType(_objSubfolder.Items(_itemCount), Outlook.PostItem)
Response.Write("Item " & _objItem.Subject.ToString)
_itemCount -= 1
End While



Kindly let me know where I am wrong
Thanks

# re: Accessing Outlook items from C# .NET 6/21/2008 5:46 AM Scott Welker
Thanks!

MailItem vs PostItem - a gold nugget. I still seek a method for determining the kind of item in a folder's Items collection so that I can cast it (or skip it). Seeks hokey to use nested "if (myItems[i] is Microsoft.Office.Interop.Outlook.<item kind>)

Anyway, thanks again!

# re: Accessing Outlook items from C# .NET 8/28/2008 9:34 PM Robbert
Johnson, you aren't releasing your COM objects so the server/client hits it's message limit of 250 items. I struggled with the same issue.

Scott, you can use Reflection to get the MessageClass of the object.

# re: Accessing Outlook items from C# .NET 9/1/2008 8:34 PM Sergey Vasiliev
Hi,

Thank you for the code.
But I did not find how to connect to the non default Exchange server?


# re: Accessing Outlook items from C# .NET 9/4/2008 9:20 PM narasiman
hi,

I cannt found the namaspace Microsoft.Office.Interop.Outlook and i am using vs 2003 and pls guide me

# re: Accessing Outlook items from C# .NET 9/19/2008 12:30 PM Peter Smith
I have the following code :


if (item is Outlook.MailItem)
{
Outlook.MailItem mailItem = item as Outlook.MailItem;
ProcessMailItem(mailItem);
}
else if (item is Outlook.PostItem)
{
Outlook.PostItem postItem = item as Outlook.PostItem;
ProcessPostItem(postItem);
}
else if (item is Outlook.MeetingItem)
{
Outlook.MeetingItem meetingItem = item as Outlook.MeetingItem;
meetingItem.UnRead = false;
}
else
{
Log("unknown item type - " + item.ToString() + " in folder:" + folder.FullFolderPath, MSPLLogMessage.Severity.critical);
}


What we actually have is an Excel object - by dragging an Excel sheet into the Outlook public folder, but our server does not have Office installed, only Outlook. So the else clause only says we have a System.__ComObject. So it doesnt know what an Excel object is. Is there any way we can mark the Excel file as read?

# re: Accessing Outlook items from C# .NET 10/2/2008 10:14 PM Peter Izuoba
Nice work,thanks.

# re: Accessing Outlook items from C# .NET 10/15/2008 6:15 PM Hemnath S
Awesome dude.Thanks

# re: Accessing Outlook items from C# .NET 10/17/2008 3:22 AM Rick
I just want to give an update on the "Unable to cast COM object of type..." error I am getting and was asking previously. This error that I was getting was caused by conflicts on items in the outlook folder that I was processing. The thing is, when you do a visual check on the items on the folder, there is no way to tell that an item was on conflict until you open it or double click on it. You have to pinpoint the actual item, open it and resolve the conflict before that item becomes a normal item again. Hope this helps cause this issue caused me real grief!

# re: Accessing Outlook items from C# .NET 11/1/2008 12:22 AM Phil
This code just sits there in the browser and doesn't retrieve anything.

It opens an Outlook object on the web server and the CPU is running at 75%, so it's doing something!

Any ideas what might be happening?

# re: Accessing Outlook items from C# .NET 12/18/2008 1:44 AM Ritesh
How can i open an attachment w/o saving it

# re: Accessing Outlook items from C# .NET 2/26/2009 2:03 AM Nic
Thanks a lot man !

# re: Accessing Outlook items from C# .NET 3/26/2009 6:57 AM Karyani
HO CAN I specify the e-mail addres I am retriveing. I have a working cod but it is retreiving only my e-mails. How can I choose a different e-mail?


Microsoft.Office.Interop.Outlook.Application oOutlook;
Microsoft.Office.Interop.Outlook._NameSpace oNs;
Microsoft.Office.Interop.Outlook.MAPIFolder oFldr;
Microsoft.Office.Interop.Outlook.MAPIFolder subFolder = null;
long iAttachCnt;
int CurrentLocationTop = 0;
int CurrentLocationLeft = 0;

public Form1()
{
InitializeComponent();
ReadMailAndSaveAttachemnt();
}
private void ReadMailAndSaveAttachemnt()
{


try
{
oOutlook = new Microsoft.Office.Interop.Outlook.Application();
oNs = oOutlook.GetNamespace("MAPI");

# re: Accessing Outlook items from C# .NET 3/27/2009 3:30 AM Sanjay
How to check for valid mail while reading a particular mail in using C#.

I am getting error for Casting

# re: Accessing Outlook items from C# .NET 3/27/2009 3:31 AM Sanjay
How to check for valid mail while reading a particular mail in using C#.

I am getting error for Casting please tell me how can i cast the mail item

# re: Accessing Outlook items from C# .NET 3/27/2009 9:37 PM Sudhakar Verma
I have one addidtional mailbox "Callworks@agilent.com" in addition to my primary mailbox "sudhakar.verma@non.agilent.com".
PROBLEM --> when i sent an email from primary mailbox to callworks then c# window service using mapi access it and marked as read.its working fine here.
But if someone else send email to callworks then window service also access it but unable to mark as read. I don't know why....Please help !!!

# re: Accessing Outlook items from C# .NET 4/30/2009 6:12 AM mohamed abdeen
i tried the above code but i have the problem of invalid cast
and get the following exception any help plz the error is
Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Outlook.PostItem'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{00063024-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).

any help ASAP

# re: Accessing Outlook items from C# .NET 5/4/2009 10:45 PM res
Hi,

Can i access the Outlook items in the exchange server from my application.?

# re: Accessing Outlook items from C# .NET 7/16/2009 12:01 PM marc
Your example saved me much time.
Thanks.

# re: Accessing Outlook items from C# .NET 8/6/2009 1:36 PM leo
Its catching "Array out of Bound" exception if the email has no attachment. how to rectify this.?

# Read Outlook 2007 categories using C# .NET 9/3/2009 4:34 AM Hemalatha
Hi
I am using .net framework 3.5 by using C# to configure outlook 2007
I need to import all categories from outlook 2007 to my application particularly on dropdownlist, i want to listed all the categories
from outlook to one combobox in my application, i don't know how to get all the categories,

pls reply me.



# re: Accessing Outlook items from C# .NET 9/29/2009 4:27 PM Ramesh
could you please let me know how we can loop though emails in outlook's .PST files saved on hard disk?

# re: Accessing Outlook items from C# .NET 11/24/2009 8:06 AM Ravichandra Chinta
Great article :)

Iused the same code in a windows service...I am trying to fetch the latest mail. But it is Access violation error is comming can you help

# re: Accessing Outlook items from C# .NET 1/21/2010 3:07 AM Slav
Hi!
I`m locked in "limit of 250 items" while reading Tasks folder.
How can i release opened items and continue searchin?
Thanks...

# re: Read Outlook 2007 categories using C# .NET 2/18/2010 1:57 AM Mehnaz Awar
Outlook.Application olApp = new Outlook.Application();
Outlook.NameSpace ns = olApp.GetNamespace("MAPI");
Outlook.Categories cat = ns.Categories;

foreach (Outlook.Category indCat in cat)
{

label1.Text += indCat.Name.ToString();

}

# re: Accessing Outlook items from C# .NET 6/21/2010 4:29 PM Zubair
The code listed so far will not work if put inside a windows service. I'm getting errors when I put the code from my console app into a windows service:

Dim objApp As Microsoft.Office.Interop.Outlook.Application = New Microsoft.Office.Interop.Outlook.Application

' Get Mapi namespace
Dim objNs As Microsoft.Office.Interop.Outlook.NameSpace = objApp.GetNamespace("MAPI")


Any ideas?

# re: Accessing Outlook items from C# .NET 6/28/2010 5:39 AM Tanveer Alam
Please Help me out ..
i tried ur code but it generating error

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

how can throw this error ...

# re: Accessing Outlook items from C# .NET 7/8/2010 4:27 AM Anand
I am also facing the same issue

# re: Accessing Outlook items from C# .NET 9/1/2010 4:34 AM pri
Use Microsoft.Office.Interop.Outlook.MailItem instead of PostITem ... that should fix the "No such interface supported" exception.

# re: Accessing Outlook items from C# .NET 10/8/2010 5:12 PM Med
thank you for giving me my first outlook interop code, and it works, after changing PostItem to MailItem.



# re: Accessing Outlook items from C# .NET 10/29/2010 8:29 AM Husnain Naz
Any can can help me. how can i use the above code to retrieve the items of my calender and how can i get the entries and display

Many Thanks,
Husnain

# re: How ro get subject - Anyone please help me.............. 11/23/2010 4:26 AM Suresh
Hi, I am trying to set the value of 'SentOn' value of a mail item using MAPI extensions, but it always throw error. Following is the code what I am using...
mailItem.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x00390040", DateTime.now)

Please help me, this is killing me...

# re: Accessing Outlook items from C# .NET 11/26/2010 8:20 AM Subhan
When i use this code in windows service it through exceptions

# re: Accessing Outlook items from C# .NET 2/12/2011 2:41 AM A.Manojkumar
'subFolder.InAppFolderSyncObject' threw an exception of type 'System.Runtime.InteropServices.COMException this exception occurs

# re: Accessing Outlook items from C# .NET 2/24/2011 7:37 AM reshma
giving error on
item = (Microsoft.Office.Interop.Outlook.PostItem)subFolder.Items[i];

Invalid cast.
Please please help!!!

# re: Accessing Outlook items from C# .NET 2/24/2011 7:38 AM reshma
error on item = (Microsoft.Office.Interop.Outlook.PostItem)subFolder.Items[i];

Invalid cast.
Please please help!!!

# re: Accessing Outlook items from C# .NET 3/1/2011 6:06 AM govardhan
it is reading without any sorted order. How can we read it in sorted order by date.


# re: Accessing Outlook items from C# .NET 3/9/2011 4:03 AM Vivek
Good Article.Thanks a lot.

# re: Accessing Outlook items from C# .NET 3/28/2011 10:31 PM Thiago
Just change to (Microsoft.Office.Interop.Outlook.MailItem).

# re: Accessing Outlook items from C# .NET 4/19/2011 5:53 AM Shrikant
How I can read specific message and save its attachement

# re: Accessing Outlook items from C# .NET 5/12/2011 11:01 AM terry
@govardhan: To sort by date, use the Sort() function on the Items collection, with the sort property being "SentOn". For an example:

Microsoft.Office.Interop.Outlook.Items theItems = subFolder.Items.Sort("SentOn",true); //true for descending, false for ascending


for(int i=1;i<=theItems.Count;i++)
{
item = (Microsoft.Office.Interop.Outlook.MailItem)theItems[i];
Console.WriteLine("Item: {0}", i.ToString());
Console.WriteLine("Subject: {0}", item.Subject);
Console.WriteLine("Sent: {0} {1}" item.SentOn.ToLongDateString(), item.SentOn.ToLongTimeString());
Console.WriteLine("Categories: {0}", item.Categories);
Console.WriteLine("Body: {0}", item.Body);
Console.WriteLine("HTMLBody: {0}", item.HTMLBody);
}



# re: Accessing Outlook items from C# .NET 5/12/2011 11:02 AM terry
Oops, my bad. Should be this:

Microsoft.Office.Interop.Outlook.Items theItems = subFolder.Items;
theItems.Sort("SentOn",true); //true for descending, false for ascending

# re: Accessing Outlook items from C# .NET 6/6/2011 12:54 AM Harish
Hi, I have integrated my component with Outlook in C# VisualStdio2008. My scenario is, im tranferring 10 contacts to outlook 'contacts' folder and i want to attach a file to all 10contacts . Im bringing the last transferred [10th] contact to forefront, and attachment is enabled only to the 10th, NOT TO THE PREVIOUS 9CONTACTS. Can anyone help ?....

# re: Accessing Outlook items from C# .NET 7/25/2011 1:14 AM SwAt
How can i specify different mail address in this exapmle ?

# re: Accessing Outlook items from C# .NET 9/23/2011 11:51 PM P.Umamaheswari
Hi, this code works fine. But every time i run this code , outlook ask to allow this to access to read email. how to handle this in coding side.? pl help me. this is urgent.

# re: Accessing Outlook items from C# .NET 9/28/2011 4:14 PM Paul R
When I try this, I get a message that ASP.NET does not have permission to access this file. What file? Not sure what file to use and how to give it permission to access it.

# re: Accessing Outlook items from C# .NET 12/1/2011 2:18 AM Ike
the code seems to work find on my machine. everytime i deploy the solution to the server it failed.

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

any help ASAP

# re: Accessing Outlook items from C# .NET 12/2/2011 11:44 AM Sankar
Regarding the _ComObject error, I ran into as well... not sure objects are being returned when accessing by the ordinal number.. maybe a calendar item, or an appointment.. but who cares.. I was interested in only inbox messages.
So, I used the very straightforward and simple logic
for (int i =1; i <=inBoxFolder.Items.Count;i++)
{
try
{
item = (MailItem)inBoxFolder.Items[i];
Console.WriteLine(item.ToString());
Console.WriteLine(item.Subject.ToString());
}
catch { }

}

# re: Accessing Outlook items from C# .NET 1/30/2012 9:25 AM Ricardo Martin
Re the comment that Terry included on 5/12/11 on how to sort items by date, I have been unable to make it work. It simply does not make any difference. It does get other info I requested like total count of items and so on.

Piece of code is as follows:
inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
inboxFolder.Items.Sort("[SentOn]", false);


Whether the Items.Sort method is included or not, it always reads the same message, and it makes no sense what order is currently in use.

Note: The items are in the main Inbox folder location, so no subfolder command is being used.

Any suggestions? Thanks

# re: Accessing Outlook items from C# .NET 3/8/2012 11:06 AM sparikh
Opening Outlook mail item code is working fine on my Local computer but its not working when i deploy it on server.I have already installed Microsoft Office and O2003PIA.EXE on server. Its not even throwing any error.

Any Suggestions ASAP. Thanks.

# re: Accessing Outlook items from C# .NET 5/21/2012 7:50 AM ankit
if i want to connect outlook out of office assistant with my own created calender,how should i proceed??

# re: Accessing Outlook items from C# .NET 6/29/2012 5:36 AM Ashish
Hi... i tried to use ur code for my outlook integration with Windows Form in C#... and i got following error...

System.Runtime.InteropServices.COMException (0x8004010F): The operation failed. An object could not be found.
at Microsoft.Office.Interop.Outlook.FoldersClass.get_Item(Object Index)
at WindowsFormsApplication1.Form1.button1_Click(Object sender, EventArgs e) in C:\Documents and Settings\shamala\My Documents\Visual Studio 2008\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs:line 50
A first chance exception of type 'System.Runtime.InteropServices.COMException' occurred in WindowsFormsApplication1.exe
The thread 0x1644 has exited with code 0 (0x0).
The thread 0x1948 has exited with code 0 (0x0).
The program '[7720] WindowsFormsApplication1.vshost.exe: Managed' has exited with code 0 (0x0).

Please Help me out...

# Track who deleted of Mail from Shared mail box from out look: Accessing Outlook items from C# .NET 7/27/2012 2:35 PM Vineet Seheju
Hi Guys,

I came into situation something like this as mentioned below and need to program accordingly.

There is one shared Inbox, on which different people work together.

So how can I track the username of the user who deleted or moved email from shared mail.

Can you please provide some link or idea?

# re: Accessing Outlook items from C# .NET 12/21/2012 6:13 AM Rohit
hi,

I want to change the message body at runtime, I have created few email message template and a outlook ribbon for the email compose window. I want that when I select any template from the ribbon the message body inside the template should be populated on the open email message body, My problem is that I don't know how can I access the compose message body which is already open, I can make a new email message at run time but this time I want to access the message body which is already open and replace the message body text with the template message text.

Please provide any link or idea, help needed...

Rohit

# re: Accessing Outlook items from C# .NET 1/8/2013 1:29 AM Subburam
I need to access or get the network id from outlook can u pls help me?

Post A Comment
Title:
Name:
Email:
Comment:
Verification: