Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the status of mail as Read in outlook

i have written a code that will read all unread mails from Outlook 2010 and write them in a file. After that i want to change the status of the mails as Read in outlook.

How do i do it?

I am using Interop for accessing the mails.

        Microsoft.Office.Interop.Outlook.Application app = null;
        Microsoft.Office.Interop.Outlook._NameSpace ns = null;
        Microsoft.Office.Interop.Outlook.MailItem item = null;
        Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;
        Microsoft.Office.Interop.Outlook.Items unreadItems = null;

        app = new Microsoft.Office.Interop.Outlook.Application();//.CreateItem(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);

        ns = app.GetNamespace("MAPI");

        inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);

        unreadItems = inboxFolder.Items.Restrict("[Unread]=true");
like image 994
Newton Sheikh Avatar asked May 09 '13 09:05

Newton Sheikh


1 Answers

Here are some link that could help you:

  • http://msdn.microsoft.com/en-us/library/aa289167%28VS.71%29.aspx (it is for Outlook 2003 but it still contains very usefull info)
  • http://msdn.microsoft.com/en-us/library/ms268731%28VS.80%29.aspx

I've a code sample that could help you:

OutLook.Application oApp;
OutLook._NameSpace oNS;
OutLook.MAPIFolder oFolder;
OutLook._Explorer oExp;

oApp = new OutLook.Application();
oNS = (OutLook._NameSpace)oApp.GetNamespace("MAPI");
oFolder = oNS.GetDefaultFolder(OutLook.OlDefaultFolders.olFolderInbox);
oExp = oFolder.GetExplorer(false);
oNS.Logon(Missing.Value, Missing.Value, false, true);

OutLook.Items items = oFolder.Items;
foreach (OutLook.MailItem mail in items)
{
    if (mail.UnRead)
    {
        mail.UnRead = false;
        mail.Save();
    }
    Marshal.ReleaseCOMObject(mail);
}
Marshal.ReleaseCOMObject(items);

// Dont forget to free all other object, using Marshal.ReleaseCOMObject then close oApp

Please note I've not tested if it works or even compile.
On of general rule with outlook dev is that you need to release ALL com object otherwise you can have strange behavior (save popup when closing outlook app, or even the outlook never close etc.)

EDIT: I would advice to you indeed use the Restrict method to get only unred mail, because my snippet above will loop in all emails which could be unnecessary and not performant.

like image 124
Fabske Avatar answered Oct 18 '22 23:10

Fabske