简体   繁体   中英

C# Outlook reading subject

I have a problem with the loop function that goes in my Inbox and shows me the subject of the emails.

private void button3_Click(object sender, EventArgs e)
        {

            Outlook.Application OutlookApp = new Outlook.Application();
            Outlook.NameSpace nameSpace = OutlookApp.GetNamespace("MAPI");
            Outlook.MAPIFolder folderInbox = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
            Outlook.Folders inboxFolders = folderInbox.Folders;
            Outlook.Items mails = folderInbox.Items;
            Outlook.MAPIFolder subFolderInbox = null;
            try
            {
                
                Console.WriteLine(" numarul de emailuri" + mails.Count);

                foreach (Outlook.MailItem item in mails)
                {

                    string subj = item.Subject;
                    MessageBox.Show(subj);
                    Console.WriteLine(subj);
                    Marshal.ReleaseComObject(item);


                }

                //subFolderInbox = inboxFolders.Add("LP History", Outlook.OlDefaultFolders.olFolderInbox);
            }
            catch (Exception exception)
            {
                if (exception.ErrorCode == -2147352567)
                //cannot creat folder error
                MessageBox.Show("Cannot creater folder error");
            }
            if (subFolderInbox != null) Marshal.ReleaseComObject(subFolderInbox);
            if (inboxFolders != null) Marshal.ReleaseComObject(inboxFolders);
            if (folderInbox != null) Marshal.ReleaseComObject(folderInbox);
            if (nameSpace != null) Marshal.ReleaseComObject(nameSpace);
                                 
        }

is doesnt even getting inside the foreach loop: what i gen inside the console: " numarul de emailuri340 'OLP.exe' (CLR v4.0.30319: OLP.exe): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_32\CustomMarshalers\v4.0_4.0.0.0__b03f5f7f11d50a3a\CustomMarshalers.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. Exception thrown: 'System.InvalidCastException' in OLP.exe"

Based on my test, I can get the subject of the emails successfully by using your code.

Therefore, I suggest that you can check the following steps.

First, please check if your current outlook app is running.

Second, please delete the reference about the outlook and reinstall it in the nuget package.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM