I'm using Outlook as email client and want to access its information through a Delphi program.
I want to retrieve the subjects from all emails in a specific folder, which is a couple of levels deep with respect to the Outlook root. I can list the email items from the root folder, but not for other folders. My current code is
procedure TForm1.BtnListMailItemsClick(Sender: TObject);
var
Outlook, NameSpace, MailRoot, Mail: OleVariant;
I: Integer;
begin
Outlook := CreateOleObject('Outlook.Application');
try
NameSpace := outlook.GetNameSpace('MAPI');
MailRoot := NameSpace.GetDefaultFolder(olFolderInbox);
for I := 1 to MailRoot.Items.Count do
begin
Mail := MailRoot.Items(I);
if (Mail.class = olMail) then
Memo1.Lines.Add(Mail.Subject);
end;
finally
Outlook := UnAssigned;
end;
end;
I guess I'll have to replace
MailRoot := NameSpace.GetDefaultFolder(olFolderInbox);
by something like
MailRoot := NameSpace.GetFolder('Outlook\Archive\Shopping');
What is the correct syntax for this?
Edit
I tried this (per Peter Wolf's comment)
MailRoot := NameSpace.GetDefaultFolder(olFolderInbox);
MyFolder := MailRoot.Folders.Item('Archive').Folders.Item('Shopping');
Memo1.Lines.Add('Folder name is "' + MyFolder.Name + '"');
MyFolder := MailRoot.Folders['Archive'].Folders['Shopping'];
Memo1.Lines.Add('Folder name is "' + MyFolder.Name + '"');
Both forms of the assignment result in an error: "An object could not be found". I also tried adding the top level:
MyFolder := MailRoot.Folders['Outlook'].Folders['Archive'].Folders['Shopping'];
but no avail. (The folders do exist.)
GetDefaultFolder(olFolderInbox)does not return the top level folder, it returns the Inbox.If the folder in question is on the same level as the Inbox, you can go one level up and then one level down to that folder:
Or you can start with the
Namespace.Folderscollection - it includes all top level folders of all message stores in the profile and drill down from there: