Reading Multiple Outlook Email for multiple IDs in C#

Viewed 1948

Referring to the answer mentioned in the post: Reading Outlook Mail with C#

This code works well for a single account, but the issue with the current code is that it reads the email of the default id which was set as the first one in the outlook app.

For example, if "abcxyz@outlook.com" is set as the first account and "decxyz@outlook.com" is set as the second one, then it reads the inbox of only the first id, i.e., "abcxyz@outlook.com". I tried doing some modifications in the code but it did not work. Below is my code:

  public static void OutLookMailStart(string EmailID, string password)
    {
        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;
        Microsoft.Office.Interop.Outlook.MailItem mailItem = null;
        try
        {
            app = new Microsoft.Office.Interop.Outlook.Application();
            ns = app.GetNamespace("MAPI");

            ns.Logon(EmailID, password, false, true);
            inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);

            foreach (Object mail in inboxFolder.Items)
            {
                if ((mail as MailItem) != null && (mail as MailItem).UnRead == true)
                {
                    // Email Subject 
                    string Subject = (mail as MailItem).Subject.ToString();
                    if (Subject.Contains(FileDomain))
                    {
                        // Email Body
                        var ReplyText = ExtractReply(((mail as MailItem).Body.ToString()), FromTrimName);
                    }
                    // (mail as MailItem).UnRead = false;
                    (mail as MailItem).Save();
                }
            }
        }
        catch (System.Exception ex)
        {
            throw ex;
        }
        finally
        {
            ns.Logoff();
            inboxFolder = null;
            subFolder = null;
            mailItem = null;
            app = null;
        }}

Any sort of help will be appreciated.

2 Answers
Related