Mail listener not seeing new mail when the terminal is locked - vba

I have Outlook VBA code that reads all incoming mails.
This code uses the MailItem to go through each mail looking at sender, to, subject and for attachments.
The heart of the code uses the urn:schemas feature that does a sql query on the inbox.
Thus if a new mail arrives the process that fires looks at the whole inbox every time and not just that mail. (The inbox is kept tidy and items are moved when processed.)
The heart of the query looks like this:
Dim Filter as String
Filter = "urn:schemas:mailheader:subject like '%That report - %'"
Dim iMailMatch As Object
Set iMailMatch = Inbox.items.Find(Filter)
The problem is that (occasionally) when the machine is locked (not logged out), the macro will fire on a new mail event, but it won't find anything even though there are mails which match.
When I unlock the terminal and a new mail arrives - the process fires and it picks up/processes mails successfully that it previously didn't see.
The problem is only apparent when the terminal is locked. Thus I can only think that it has to do with kind of trust privileges.
There are times is does fire successfully when the terminal is locked, but it appears to be only when a mail arrives soon after the terminal is locked.

Do not search. NewMailEx event passes the entry id of the new item to your event handler - open the item using Namespace.GetItemFromID, then read the MailItem.Subject property.

Related

Outlook VBA - Create an email, allow the user to send, then execute further code

I have an outlook Macro that collects some information from existing emails and a local database, then serves up a templated email with the information. The user can then review the email, make changes if they want to and then send or not sent (quit/cancel). Is there a way, I can keep the macro running and then execute more code if the user sends the email?
I've created some psuedo code below on how I'm hoping it might work:
Function CreateEmailThenExecuteCode()
Dim newEmail As MailItem
Set newEmail = Application.CreateItem(olMailItem)
newEmail.Display
'Allow user to review and send email
'If they 'send', then execute further code.
If Not Sent Then Exit Function
'Further code
End Function
I know that I can create a new macro that runs every time a user sends an email - but it would be much easier if I can keep the existing macro running, as otherwise I need a way of saving the data from the running macro.
I also know that I can create a custom user form that mimics an email user form - but I would prefer to keep the functionality of the full email user form, especially with access to email address lists etc.
Is it possible?
The Display method doesn't prevent your code from running until you pass true to make the Inspector window modal. The default value is false.
At the same keeping the code running after the Display call doesn't allow users to deal with Outlook UI because the VBA code will be run on the main thread (UI).
You may consider setting up an event handler for the Send event which is fired when the user selects the Send action for an item, or when the Send method is called for the item. So, you will be aware when the item is sent out.
Also you may find the MailItem.Close event helpful. It is fired when the inspector associated with an item is being closed. So, you will also be aware when the item is closed.

Verify if an Outlook Email Sent From VB.net was Actually Sent

I'm writing some code in VB.net which will zip some files with a password & email them to the recipient(s) & then send a second email to the recipient(s) with the password for the zip file. The email is sent through Outlook.
The people who would be using this also have some VBA code in the Application_ItemSend event procedure in Outlook which checks if there's attachments being sent to external email addresses & if so it gives the user the details & the option to Cancel sending the email - this is done using the Cancel property/argument (sorry I'm not good with the correct terminology for things in VBA/VB.net) of the Application_ItemSend event procedure.
If the user does cancel the first email then I'd like to stop the second email from going out aswell. I've tried checking (directly after invoking MailItem.Send()) MailItem.Sent.ToString but it bugs out on that line & gives this exception - System.Runtime.InteropServices.COMException: 'The item has been moved or deleted.
My first thought was that once MailItem.Send() was invoked that MailItem became nothing, but I've just put a watch for MailItem Is Nothing & it's returning False. I've tried searching but not been able to find anything.
I can work around by displaying the second email & leave it to the user to send or cancel but if possible I'd rather have the code take care of it.
Instead of sending the second email immediately, wait until Items.ItemAdd event fires on the Sent Items folder. Once the first message raises that event, you can create and send the second email.

How to Send All Emails From Outlook Outbox in VBA

I'm using Excel VBA to stage emails in Outlook and it is working well.
Dim template As Outlook.MailItem, tomerge As Outlook.MailItem
' Create E-mail
tomerge.Close olSave
The e-mails can then be manually moved to the Drafts folder and sent using this Sub.
'Loop through items in Drafts folder
objDrafts.Item(i).Send
However, many users have a bunch of extra drafts in their Drafts folder that they don't want sent.
If I replace "olFolderDrafts" with "olFolderOutbox" and try to send from their Outbox. The first message sends and then I get a "Run-time error" "Outlook has already begun transmitting this message".
Is there some way to send all from the Outbox or even better is there someway to stage and send from a newly created folder?
You need to create a folder for your unsent items and process them separately. As a rule the Outbox folder contains already submitted items. So, that's not a right place for your items.
The Outlook Object Model provides the Add function of the Folders class. You can get an instance of the Folders class using the Folders property of the Folder class in Outlook. You can read more about that in the How To: Create a new folder in Outlook article.
This answer was inspired by Nagarajan's comment above, but there are quite a few changes necessary from the answer in Send/Receive in Outlook Via Code. The main problem is using olSave doesn't put the messages in a "ready to send" state in Outlook so starting a sync using syc.Start from the answer above does nothing.
Instead, we found the following process to be straight forward:
Put Outlook in offline mode using "Send/Recieve" -> "Work Offline"
Use Excel VBA to stage the e-mails and instead of saving just .Send each email. As Outlook is offline they will be staged and ready to be sent but not actually sent.
The e-mails should now be staged in Outlook's Outbox folder and can be reviewed just be sure to press the "send" button after reviewing/editing messages otherwise the e-mail you modified will be removed from the queue.
When the messages are ready to be sent put Outlook back in online mode and they will be sent automatically.

WithEvents object in Outlook VBA eventually fails to raise event

Okay, looks like someone has encountered this problem before, but I didn't see any further comments or solutions. See the Edit in the accepted answer to this question.
My situation is like this.
I am running Outlook 2013 under Win10 x64 with an Exchange email account. I sometimes run Outlook for several days to a week or more at a time without closing it.
I want to raise an event when a new item is added to the Sent Mail folder. This needs to occur after the Application ItemSend event because, let's say, I want to delete the message after it is sent, which you cannot do from within the ItemSend event handler.
So I have the following code:
Public WithEvents goSent As Outlook.Items
Private Sub Application_Startup()
'Establish the global object for the folder we want to monitor.
Set goSent = Session.GetDefaultFolder(olFolderSentMail).Items
End Sub
Private Sub goSent_ItemAdd(ByVal Item As Object)
'Do stuff here.
End Sub
Everything works beautifully for a day or longer, but eventually the ItemAdd event handler stops firing. If I enter the VBA editor and manually run Application_Startup, then it starts working again.
[Edit:] One other bit of information: The "built-in" events, like Application ItemSend, always seem to fire reliably no matter how long Outlook has been running.
[Edit 2:] This time, I let things go for a day after the event stopped firing. I opened the VBA editor and put a breakpoint in the Application ItemSend procedure. When it stopped, I queried the goSent object and found that (a) it still existed (rather than being Nothing), but (b) it had only the items in it that were there yesterday, presumably at the time it became "untethered" from the Sent Mail items collection. When I submitted a new Set statement in the Immediate window, it immediately began to work again.
[Edit 3:] I noticed that the MSDN documentation says to put event handlers for custom objects--like my ItemAdd event--in class modules. I have mine in ThisOutlookSession, but it was my understanding that ThisOutlookSession is a class module. Is there a problem with that?
Any idea why this would happen and what to do about it? I considered adding an event handler for Application ItemSend and just reassigning the goSent object every time that's fired, but it doesn't address the underlying problem.
[Edit 4:] For a while now, I've had a Set statement in the Application ItemSend handler, and that seems to have mostly taken care of things, even though it's a workaround, not really a solution. It appears to fail when I have delayed delivery on a sent item for an extended time, and I don't send any further messages in the meantime. Then the goSent object disconnects from the Sent Mail collection, and the message is actually sent from the Outbox after that point and before Application ItemSend fires again.
Thanks!
[Edit 5:] Unrelated to original issue: I discovered that my macros fail to accomplish what I want with an Exchange server that is in online mode (i.e., not cached mode) if I have messages in the Outbox with delayed delivery and Outlook is closed when the delivery time passes. In online mode, Exchange itself sends these messages and adds them to the Sent Mail folder on the server, so when Outlook reopens, the messages are already in the Sent Mail collection and no event fires. Which makes sense. See discussion here. Looks like I would need to add something to my Application_Startup macro to look for messages sent since Outlook last closed.
I had similar issue and never found a proper solution. What I did was I wrote a little batch script that closes and opens outlook app, then I set a task in task scheduler to run it every hour outside of my working hours. You can also do it easily in vbs.

How can the Add.Item event works at Outlook opening?

I got an issue with the macro I did in Outlook. To resume, the macro starts every time I receive an email. Then it will run a few others Sub, modify an Excel file and so one. When Outlook is running and I receive a new email, everything works perfectly. The problem occurs when I open Outlook and I receive more than one email at the same time.
I suppose the macro doesn't have enough time to end what it's doing with the first email and already try to start again with the next one.
Is there a way to keep the next emails in suspend in order to run the macro for each email, each one has its turn ? Or maybe you have another solution ?
Thank you.
PS: I can provide the code but it's very long.
The problem occurs when I open Outlook and I receive more than one email at the same time.
The NewMailEx event of the Application class is fired once for every received item that is processed by Microsoft Outlook. The item can be one of several different item types, for example, MailItem, MeetingItem, or SharingItem. The EntryIDsCollection string contains the Entry ID that corresponds to that item.
The NewMailEx event fires when a new message arrives in the Inbox and before client rule processing occurs. You can use the Entry ID returned in the EntryIDCollection array to call the NameSpace.GetItemFromID method and process the item.
Make sure VBA macros are enabled and allowed to run when Outlook is started. Check out the Trust Center settings in Outlook.