Detect if public folder (of exchange) exists in Outlook
-
22-10-2019 - |
Question
With the following Code-Block you select the public folder which is set in Outlook:
const
olPublicContactsFolder = $00000012; //constant for the public folder
begin
Outlook := CreateOleObject('Outlook.Application');
// Get name space
NameSpace := Outlook.GetNameSpace('MAPI');
// Get root public folder
ContactsRoot := NameSpace.GetDefaultFolder(olPublicContactsFolder); //<-- Error
Contacts:= Contactsroot;
An error occurs on the marked line if there is no public folder in Outlook (no public folder set in Outlook, no Exchange Server).
The question is how to avoid that error by previously detecting if there is a public folder set or not.
Catching the error with a try...finally/except block didn't work as the exception is caused externally by the Microsoft API (EOleException).
I can't think of another way to detect if the folder exists as the line causing the error is essential in selecting the public folder and therefore getting properties of it.
greetings
Solution
Why wouldn't try/except work? Delphi catches EOleSysError exceptions just fine. And the exception is raised by the Delphi RTL, not Outlook - all IDispatch-friendly libraries return an error code, which the RTL converts to an OLE exception after requesting the description using IErrorInfo.
OTHER TIPS
As the message indicates, Outlook doesn't know which profile to use. You need to logon to the MAPI namespace before you can do anything with it. You need to do this even if there is no logon information for example when you connect to a local Outlook instance that is not connected to an Exchange server.
FNameSpace := FOutlook.GetNamespace('MAPI');
FNameSpace.Logon('', '', False, False);
Folder := FNameSpace.GetDefaultFolder( olFolderCalendar );
Memo1.Lines.Add( 'Calendar: ' + Folder.Name + ': ' + Folder.Description );
This Codeblock does work just fine. I figured I had another issue which I resolved. Thanks for your time.
function DoesPublicFolderExist():Boolean;
const
olFolderContacts = $00000012;
var
Outlook, Namespace, ContactsRoot, Contactsfolder : OleVariant;
begin
// Connect to outlook
Outlook := CreateOleObject('Outlook.Application');
// Get name space
NameSpace := Outlook.GetNameSpace('MAPI');
// Get root contacts folder
try
ContactsRoot := NameSpace.GetDefaultFolder(olFolderContacts);
Result:= True;
except
Result:= False;
end;
end;
Dmitry Streblechenko was quite right with his answer, I just mistook the EOleException of the Debugger for an external one. Running the Code without the Debugger doesn't lead to the Exception as it indeed gets catched by the try/exception block.
Marjan Venemas answer might come handy when working with multiple accounts in Outlook.