2
votes

My situation:

I'm trying to send e-mails while Outlook is not open. This code will work if Outlook is running. If Outlook is closed the code will create a non-visible process that you can see running in Task Manager.

The code encounters an error during the .Send. It returns runtime error 287.

From my experience that are certain VBA methods that will only work when the object is either visible or active.

My work around is to use .Display(False) before calling .Send.

After calling .Send it immediately terminates the Outlook process. (Please point me to the right direction why.) Then the e-mail gets stuck in the Outbox.

I have to apply another work around by calling another CreateObject("Outlook.Application") and either looping through the Outbox While Outbox.Items.Count > 0

or

Looping through SyncObjects and manually calling .Start to run Send/Receive on the Outbox.

My question:

Is there a way to directly use the .Send method instead of using work arounds while also not having to open Outlook.

My code:

Sub emailer()

Dim OutApp As Object
Dim OutMail As Object

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

With OutMail
    .to = "[email protected]"
    .CC = ""
    .BCC = ""
    .Subject = "This is the Subject line"
    .Body = "Hi there"
    .Send   'or use .Display
End With

Set OutMail = Nothing
Set OutApp = Nothing

End Sub
2
try putting the "While Outbox.Items.Count > 0" loop into your code right after the "End With" linejsotola

2 Answers

1
votes

Use Namespace.SendAndReceive. Keep in mind that Send/Receive is asynchronous and you need to wait to the sync to finish. You can use Namespace.SyncObjects collection, start a sync using SyncObject.Start, then wait for the SyncObject.SyncEnd event.

To prevent Outlook from closing, you need to keep a live reference to an Outlook Explorer or Inspector object. You can retrieve the Inbox folder using Namespace.GetDefaultFolder, then use MAPIFolder.GetExplorer method to get a pointer to an Explorer object.

UPDATE:

You might also want to make sure that you log to a MAPI profile before you create and send a message. After the CreateObject line, try to add the following

set NS = OutApp.GetNamespace("MAPI") 
NS.Logon
2
votes

A workaround for the .send issue with Outlook closing can possibly be resolved by changing the settings for Send/Receive. Go to File -> Options -> Advanced -> find Send/Receive... and press it. Under "Setting for group "All Accounts" is a checkbox for Perform an automatic send/receive when exiting. Check this, and it may resolve the "stuck in the outbox issue you are having".

Here is a screenshot:

Give this a try, hopefully it helps.