'How to access Outlook email by a Delphi subthread

I use this to access Outlook emails in a subthread:

try
  Outlook := GetActiveOleObject('Outlook.Application') ;
except
  Outlook := CreateOleObject('Outlook.Application') ;
end;
NameSpace := Outlook.GetNameSpace('MAPI');
Folder := NameSpace.Folders;

After finding the specified folder I access emails in a loop by a:

var MailItem: Variant;
MailItem := Folder.Items[i];

Then I use the list of mail items in my application to access them. This works in the main thread or in the subthread itself. But when I pass MailItem obtained from a subthread to the main thread I get an excepion. It seems that Folder.Items returns a pointer that is strictly assigned to the subthread and is not accesible from the main thread.

How should I get a long list of emails not to block the main thread? I want something nicer than Application.ProcessMessages;



Solution 1:[1]

Where is your code running? Is it a standalone exe or a COM addin? Keep in mind that Outlook 2013 will raise an exception as soon as it detects that is object is being used rom a thread other than its main thread (in case of a COM addin). In case of a standalone exe, all calls are marshaled to the main Outlook thread anyway, so you are not gaining anything by using secondary threads.

You can use Extended MAPI or a MAPI wrapper (such as Redemption - I am its author) - its RDO family of object is thread safe.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1