0
votes

I am currently having an issue around automatically sending emails via excel vba? I have a simple example:

Sub sendOutlookEmail()

Dim oApp As Outlook.Application
Dim oMail As MailItem
Set oApp = CreateObject("Outlook.application")

Set oMail = oApp.CreateItem(olMailItem)
oMail.Body = "Body of the email"
oMail.Subject = "Test Subject"
oMail.To = "[email protected]"

oMail.Send

Set oMail = Nothing
Set oApp = Nothing

End Sub

This works fine when an outlook client is open. When outlook is closed I receive the following error:

Error 287: Application-defined or object-defined error

Now if I add a single line of inconsequential code above the oMail.Send Command:

Debug.Print oApp.Session.Accounts.Item(1).DisplayName

Now the code works fine regardless of Outlook open or closed.

I am aware that Windows Authentication is required to auto send an email via the OLE when Outlook is closed and is using LDAP, but as the extra code is unchanging of the sub routine. I believe this is some sort of bug around the initialisation of the Outlook.application.Session.Account default object.

Could you please help is this an LDAP issue or a Outlook.Application class issue, This is a replicated error from a VB app that I do not have access to the source code for, but is behaving in the same way and reporting the same error.

Thank You

2

2 Answers

3
votes

The reason for this behaviour is stated here:

http://msdn.microsoft.com/en-us/library/office/ff861594%28v=office.15%29.aspx

Code example-

' Start Outlook.
Dim olApp As Outlook.Application
Set olApp = CreateObject("Outlook.Application")

' Get a session object. 
Dim olNs As Outlook.NameSpace
Set olNs = olApp.GetNamespace("MAPI")

' Create an instance of the Inbox folder. 
' If Outlook is not already running, this has the side
' effect of initializing MAPI.
Dim mailFolder As Outlook.Folder
Set mailFolder = olNs.GetDefaultFolder(olFolderInbox)

' Continue to use the object model to automate Outlook.

"Starting in Outlook 2010, if you have multiple profiles, you have configured Outlook to always use a default profile, and you use the Logon method to log on to the default profile without prompting the user, the user will receive a prompt to choose a profile anyway. To avoid this behavior, do not use the Logon method; use the workaround suggested in the preceding InitializeMAPI example instead."*

The 'workaround' as Microsoft calls it is to simply make a statement to the Namespace object. This initializes the MAPI. It appears that when communicating remotely through the OLE interface, the Outlook application object might not be visible and the prompt to choose a profile might not be displayed, giving the appearance that nothing is happening.

Thanks Mark for helping me to identify the problem.

Tom Feuerstake

0
votes

Try to add a call to Namespace.Logon:

Set oApp = CreateObject("Outlook.application")
set oNS = oApp.GetNamespace("MAPI")
oNS.Logon