6

I'm trying to use Microsoft.Office.Interop.Outlook to retrieve emails from my Outlook inbox. This is my code:

  Application app = new Application();
  NameSpace ns = app.Session;
  MAPIFolder inbox = ns.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
  Items items = inbox.Items;
  foreach (Microsoft.Office.Interop.Outlook.MailItem mail in items)
        {
            if (mail as MailItem != null)
            {
                Console.WriteLine(mail.Subject.ToString());
                Console.WriteLine(mail.Body.ToString());
                Console.ReadKey();
             }
        }

When I do this, it works--sort of. It only shows one email. There should be three. The email it's showing is the oldest one in there... why wouldn't I be able to get all three? Is there some other type of mail besides MailItem that would be in my inbox?

eddie_cat
  • 2,527
  • 4
  • 25
  • 43

1 Answers1

8

I had this same exact problem - My workaround was just to create a List<MailItem> and loop through that. Make sure the emails aren't in subfolders though, otherwise they won't be found.

Outlook.Application app = new Outlook.Application();
Outlook.NameSpace outlookNs = app.GetNamespace("MAPI");
Outlook.MAPIFolder emailFolder = outlookNs.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);

List<MailItem> ReceivedEmail = new List<MailItem>(); 
foreach (Outlook.MailItem mail in emailFolder.Items)               
    ReceivedEmail.Add(mail);

foreach (MailItem mail in ReceivedEmail)
{
    //do stuff
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
ovaltein
  • 1,185
  • 2
  • 12
  • 34
  • This code tends to throw errors for me. The first foreach should loop through objects instead of assuming they're MailItem type. Inside the loop before casting you should check each item's type. – DAG Jan 21 '20 at 16:37
  • Had the same issue. Worked for me, thanks. Strange that it doesn't work the simple way. – Juri Mar 03 '20 at 08:25