Script triggered by email Rule to save attachment intermittently gives "Unexpected error has occurred" and the rule switches off - vba

I have a VB script that is triggered by a rule that saves the email's attachment to a specific folder. The rule runs ok for a period and then I receive the Outlook error message: "Unexpected error has occurred" and the rule is switched off.
Whilst I can't definitively say, from observations it seems that the error is more likely to occur when I receive more than one of these emails in the same send/receive batch. The attachments are usually 2MB to 5MB in size, and at times the Email Subject lines & file names on each of the consecutive emails' attachments can be the same. The same script on another rule which is usually only triggered once daily doesn't throw the error and continues working without interruption. This is occurring on multiple machines - so I deduce this might be related to the way Outlook handles these specific emails.
I don't know how to debug this situation and more frustratingly I haven't been able to find a post with a similar problem from my web searches.
Would appreciate any hints on what might be going on here... or even how you would approach debugging?
Public Sub SaveAttachmentsToDisk(MItem As Outlook.MailItem)
Dim oAttachment As Outlook.Attachment
Dim sSaveFolder As String
sSaveFolder = "C:\RawFiles\"
For Each oAttachment In MItem.Attachments
If UCase(oAttachment.DisplayName) Like "*.XML" Then
oAttachment.SaveAsFile sSaveFolder & oAttachment.DisplayName
MItem.UnRead = False
MItem.Delete
End If
Next
End Sub
OUTLOOK RULE:

Related

Macro for saving a local copy of a mail (and renaming the local copy)

Company i work for manually saves certain requests (sent per mail) to a shared drive, renaming them as such: "YYYYMMDD_Firstname_Lastname". The mails are saved as .msg
Since we get about a hundred of these per week, I'd like to macro this so I don't waste time.
The article here: Outlook VBA macro for saving emails copies in a local folder explains how to save files locally, but I'd like to make following additions:
- Rename the copy before it gets saved to the shared drive (manually if needed)
- Select the shared path it needs to be saved to (preferably a drop-down with three choices)
- create a proper userform for this
If anyone could assist with the code, or provide me with tutorials/guides on how to do this myself, I'd be extremely grateful.
P.S. just started using and creating macro's a week ago. Still very much a beginner. any link to a good tutorial for developers would be greatly appreciated, regardless of whether it answers my questions.
Thanks guys!
Used the code described in the article as such:
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Call SaveACopy(Item)
End Sub
Sub SaveACopy(Item As Object)
Const olMsg As Long = 3
Dim m As MailItem
Dim savePath As String
If TypeName(Item) <> "MailItem" Then Exit Sub
Set m = Item
savePath = "c:\users\your_user_name\desktop\" '## Modify as needed
savePath = savePath & m.Subject & Format(Now(), "yyyy-mm-dd-hhNNss")
savePath = savePath & ".msg"
m.SaveAs savePath, olMsg
End Sub
Update: using the macro provided by Tony Dallimore I've amanaged to identify that .SenderName is the main info I need from the mails to be processed. All I need now is to replace the spaces in that output by underscores, and add the date in reverse in front of it to have my filename.
Thanks a bunch to Tony Dallimore for the continuous assistance on this project.
Since it seems somewhat confusing looking back on my original question, I'll try to clarify:
I get about 100 mails a week informing us of approvals of certain user requests.
Company policy is to save these mails as .msg on a shared drive used for administration before processing the request. The filename of these messages needs to be as such:
"YYYYMMDD_FIRSTNAME_LASTNAME.msg" (with YYYY being the year, MM being the month, and DD being the day on which we received these mails)
We get three main "types" of such mails, saved in different locations, but using the same filename respectively.
What I'd need is a macro or set of macros that can save these mails in the correct networkdrive under the correct format at the press of a button, or using minimal clicks/manual input.
I've decided to use .SenderName and .Senton, since those seem to give me most of what I need.
This is not a direct answer to your question. It is an investigation which I hope will provide the information necessary for an answer.
You say “… mails are auto-generated by the system …”. This may explain why I do not fully understand why your code works. I will explain my confusion after I have provided some background.
There are four distinct methods by which a MailItem can be selected for processing:
The user can select one or more emails and then call a macro to process the selected MailItem. (Note it is an email to the user but a MailItem to a macro.)
A macro can read up or down a folder of MailItems, reviewing properties to determine which are to be processed. Sort and Filter can be used to more quickly target the MailItems of interest.
You can specify a rule that will look at each email as it arrives and review properties such as subject and sender. If the email has the required properties, a number of actions can be performed. If the standard actions are not adequate, you can link a macro to perform any action available to a VBA macro.
You can instruct Outlook to call a macro whenever a particular event occurs. Events include: MailItem added to folder Xxxx,MailItem opened, MailItemsent, MailItemsaved, MailItem closed, MailItem replied to or MailItem forwarded.
Your code is using approach 4. In particular, you are using a MailItemsent event. You say “ … we get about a hundred of these [emails] per week …”. If “get” is the correct word, I would expect MailItem added to folder Inbox to be the appropriate event. Perhaps your code works because the system is generating emails from user X to user X.
If these emails are generated by the system, we cannot be sure what properties are set and what values they are set to. Please copy the code below to an Outlook module. Select one or more of these emails and run macro CallSubForSelectedEmails.
Option Explicit
Public Sub CallSubForSelectedEmails()
Dim Exp As Explorer
Dim ItemCrnt As MailItem
Set Exp = Outlook.Application.ActiveExplorer
If Exp.Selection.Count = 0 Then
Call MsgBox("Please select one or more emails then try again", vbOKOnly)
Exit Sub
Else
For Each ItemCrnt In Exp.Selection
If ItemCrnt.Class = olMail Then
Call DsplSimpleProperties(ItemCrnt)
End If
Next
End If
End Sub
Sub DsplSimpleProperties(ItemCrnt As Outlook.MailItem)
Dim InxR As Long
Debug.Print "=============================================="
Debug.Print " Profile: " & Session.CurrentProfileName
Debug.Print " User: " & Session.CurrentUser
With ItemCrnt
Debug.Print " Created: " & .CreationTime
Debug.Print " Receiver: " & .ReceivedByName
Debug.Print " Received: " & .ReceivedTime
For InxR = 1 To .Recipients.Count
Debug.Print "Recipient: " & .Recipients(InxR)
Next
Debug.Print " Sender: " & .Sender
Debug.Print " SenderEA: " & .SenderEmailAddress
Debug.Print " SenderNm: " & .SenderName
Debug.Print " SentOn: " & .SentOn
Debug.Print " Subject: " & .Subject
Debug.Print " To: " & .To
End With
End Sub
For one of my emails, this routine outputs:
==============================================
Profile: Outlook
User: Tony Dallimore
Created: 08/04/2019 19:59:22
Receiver: Tony Dallimore
Received: 08/04/2019 18:45:39
Recipient: a.j.dallimore#acmeisp.com
Sender: Lifecake
SenderEA: support#lifecake.com
SenderNm: Lifecake
SentOn: 08/04/2019 18:45:37
Subject: ?? Someone commented on Alex and Eric's video
To: a.j.dallimore#acmeisp.com
Note 1, I am both the system user and the receiver of this email. This gives two possible ways of getting my first and last names. I use initials in my email address but your company may use names.
Note 2: my code uses approach 1 to select the emails to be processed. Macro CallSubForSelectedEmails calls macro DsplSimpleProperties for each selected email. I do all my investigations and all my development of email processing macros using code like this. This gives me complete control over which emails are processed. The call profile for macro DsplSimpleProperties is the same as that for a rule macro or an event macro. Once I have debugged my macro using approach 1 and switch to calling it from a rule or an event with minimal additional testing. I know of no easier way of debugging email processing macros.
Again this is not a complete answer because I do not have the information for a complete answer.
Task 1: Generate PathName
The information for the path name comes from the MailItem's Subject. For this example, I assume the request type is 1, 2 or 3 and it is the last character of the subject.
Dim PathName As String
' Generate end of subfolder name
Select Case Right$(ItemCrnt.Subject,1)
Case "1"
PathName = "xxxx"
Case "2"
PathName = "yyyy"
Case "3"
PathName = "zzzz"
Case Else
' Subject does not conform to expected format.
Exit Sub
End Select
' Prefix root folder name and year of subfolder name
PathName = "P:\EMEA Requests\" & Year(ItemCrnt.SentOn) & "\" & PathName
Right$ is a function that extracts a specified number of trailing characters from a string. Functions Left$ and Mid$ are also available. If the subject is sufficiently complicated, we can consider Regex. Year is a function that extracts the year from a date. The value will be an integer but VBA will automatically convert it to a string if it used as a string.
If the routine cannot identify the request type, it abandons the MailItem. I will discuss this issue later.
Task 1; Suggestion 2: Generate PathName
You say the subjects lack a fixed format and just include words from the original request. You imply these words are good enough for a human to identify the request type. So the words for a request might include "hardware", "h'ware", "computer" or "laptop". Another request might include "software", "application or "app". This is a simple method of handling this type of situation. There is a better method which I will introduce if this looks feasible.
If Instr(1, LCase(ItemCrnt.Subject), "hardware") <> 0 Then
PathName = "xxxx"
ElseIf Instr(1, LCase(ItemCrnt.Subject), "h'ware") <> 0 Then
PathName = "xxxx"
ElseIf Instr(1, LCase(ItemCrnt.Subject), "computer") <> 0 Then
PathName = "xxxx"
ElseIf Instr(1, LCase(ItemCrnt.Subject), "laptop") <> 0 Then
PathName = "xxxx"
ElseIf Instr(1, LCase(ItemCrnt.Subject), "software") <> 0 Then
PathName = "yyyy"
ElseIf Instr(1, LCase(ItemCrnt.Subject), "application") <> 0 Then
PathName = "yyyy"
ElseIf Instr(1, LCase(ItemCrnt.Subject), "app") <> 0 Then
PathName = "yyyy"
Else
PathName = ""
End If
You can keep adding possible keywords until your requestors run out of alternatives. Failing that you can use your userform with buttons approach after the macro has handled the easy messages.
Task 2: Generate FileName
Dim FileName As String
FileName = Format(ItemCrnt.SentOn, "yymmdd") & " " & Replace(ItemCrnt.SenderName," ", "_")
Task 0: Design
Before coding can start, you need to design the total process. You can start with something simple and then develop it as you better understand your requirement. You can code little bits as I did with PathName and FileName so you can understand the bits you need to fit together. But tackling something complex without a plan rarely ends satisfactorily.
My understanding of your requirement is incomplete but I will have a go at a design.
I would have a Rule that copied incoming emails of this type to an Outlook folder such as "Unsaved EMEA Requests". Note: these are copies; the original remains in the Inbox for processing as required. I assume there is a way to identify these emails that is within the functionality available to a rule.
I would have all the code in a macro which I would call once or twice a day as appropriate. This macro would read up folder "Unsaved EMEA Requests". If it can generate a path and file name for a message, it will save the message to the required disc folder and delete the message from the Outlook folder. If it could not process a message, it would leave it in Outlook folder "Unsaved EMEA Requests". If a message is left in Outlook folder "Unsaved EMEA Requests", you will know (1) that the macro needs enhancing to handle a previously unencountered message type or (2) the rule needs amending because it has copied the wrong sort of message.
I said "read up folder" not "read down folder". You access a MailItem within a folder by its position: 1, 2, 3, … Folder.Count. If you delete MailItem 2 then MailItem 3 becomes MailItem 2, MailItem 4 becomes MailItem 3 and so on. The value of Folder.Count is reduced by one. You sometimes see questions asking why their macro is only processing every other MailItem. The reason is they have coding like:
For InxI = 1 to Folder.Count
' Process and delete Folder.Item(InxI)
Next
With the above code, you process items 1, 2, 3 in turn. If you delete item 2, you will skip the original item 3 because it is now item 2.
The correct code is:
For InxI = Folder.Count To 1 Step -1
' Process and delete Folder.Item(InxI)
Next
With this code you process items 10, 9, 8, 7 in turn. If you delete item 9, you do not care that item 10 has become item 9 because you are now processing item 8.
If you are only reading items, you do not need to worry above this issue. But if you are adding or deleted items, you do need to worry about it.

MS Outlook VBA to upload email attachment to a Sharepoint with authentication

I'm still sort of a beginner in using VBA and I've been trying to figure out how to upload a file via VBA in MS Outlook to a Sharepoint. I've tried mapping the Sharepoint to my Network Drive and such but to no avail.
My code is as follows:
Public Sub saveAttachSentDate(MItem As Outlook.MailItem)
Dim oAttachment As Outlook.Attachment
Dim sSaveFolder As String
Dim file As String
Dim DateFormat As String
sSaveFolder = "(URL of the sharepoint along with the folder to save it on)"
For Each oAttachment In MItem.Attachments
DateFormat = Format(MItem.SentOn - 1, "mm.dd.yy ")
file = sSaveFolder & DateFormat & oAttachment.DisplayName
oAttachment.SaveAsFile sSaveFolder & DateFormat & oAttachment.DisplayName
Next
End Sub
My File Name is labelled like this: "[My Department] - (Client Name) Telephony Summary"
I always get this error
"Run-time error '2147024735 (800700a1)': Cannot save the attachment. File name or directory name is not valid."
I'm thinking that the probable cause is that the sharepoint I'm uploading to requires a username and password every time you access it. I tried another sharepoint using the same exact code that doesn't require login credentials and it works just fine. I can't seem to find a work-around and I'd appreciate any help!
The path passed to the SaveAsFile method can't be represented by the URL string or network location. You need to specify a local folder from which you can start uploading files. The Outlook object model doesn't provide anything for uploading files to any web servers, so you will have to do that on your own. To get that working I'd recommend developing a COM add-in. For example, VSTO based add-ins are built on top of .net framework and can use BCL classes to deal with that. See Walkthrough: Create your first VSTO Add-in for Outlook to get started quickly.

Outlook script moves attachments to folder but goes newest to oldest

I have a script within Outlook that moves an attachment to a folder. The folder is actually SharePoint Online so the file in the attachment is posted to our SharePoint site daily. It works perfectly Monday through Friday when the email is received.
Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
saveFolder = "C:\Users\xxx\SharePoint\Systems-Information Technolog - SYS 1\xxx"
For Each objAtt In itm.Attachments
objAtt.SaveAsFile saveFolder & "\" & objAtt.DisplayName
Set objAtt = Nothing
Next
End Sub
However, on Monday when the attachment is received and the rule is activated the attachment for Monday is posted to SharePoint, then the attachment for Sunday is posted and then the attachment for Saturday is posted making the only file available on SharePoint 2 days old.
I realize I can have the report stop arriving on Saturday and Sunday but can the script be modified to only retrieve the most recent attachment and then not run again? The reason this could be important is the attachment in the future could be created multiple times a day so I would need the most recent and no other to be posted.
Thanks for your help!
You can check out the RecievedTime property of the MailItem class which returns a Date indicating the date and time at which the item was received. So, you can check out the received time of each incoming email and save the attachment only if the mail item is the most recent one.
What kind of rule? After the message arrives? Keep in mind that if Outlook is not running, it will not receive new mail motivations (Saturday and Sunday). When Exchange cached store syncs with the server (on Monday), you will see new unread messages in the Inbox, but there will be no new mail motivations and the new mail rules will not fire.
You will need to change your code to run in response to the Items.ItemAdd event on the Inbox folder or run your code manually and process unread messages in the Inbox.

How to send a same reply mail (template saved in outlook) to the mail sender (to, cc)?

I am receiving continues emails from customer (different customers) to update their asset details in database.. once process done .. I have to reply (including cc) from their mail telling like "asset details successfully stored in Database" (am using template) using VBA.
Option Explicit
Public Sub ReplyToAll()
Dim oExp As Outlook.Explorer
'for selected mails in outlook
Dim oSM As mailItem
Dim oNM As mailItem
On Error GoTo Err
Set oExp = Outlook.Application.ActiveExplorer
'Check if something is selected
If oExp.Selection.Count > 0 Then
'Get the first item selected
Set oSM = ActiveExplorer.Selection.Item(1)
'Create a Reply template
Set oNM = oSM.ReplyAll
With oNM
'Change the subject
.Subject = "RE: " & oSM.Subject
'Change the body
.Body = .Body & Chr(13) & Chr(13)
'Display the new mail before sending it
.Display
End With
End If
Exit Sub
Err:
MsgBox Err.Description, vbCritical
End Sub
section 3
Sub ReplyAll()
Dim objOutlookObject As mailItem
For Each objOutlookObject In GetCurrentOutlookItems
With objOutlookObject
.ReplyAll.Display
'prob area code does not include the template saved in the location c ..throws some error
.createitemtemplate("c:\car.jtm")
End With
Next
End Sub
Function GetCurrentOutlookItems() As Collection
Dim objApp As Outlook.Application
Dim objItem As Object
Dim colItems As New Collection
Set objApp = CreateObject("Outlook.Application")
On Error Resume Next
Select Case TypeName(objApp.ActiveWindow)
Case "Explorer"
For Each objItem In objApp.ActiveExplorer.Selection
colItems.Add objItem
Next
Case "Inspector"
colItems.Add objApp.ActiveInspector.CurrentItem
Case Else
' anything else will result in an error, which is
' why we have the error handler above
End Select
Set objApp = Nothing
Set GetCurrentOutlookItems = colItems
End Function
I am sorry my comment was so curt; 500 characters does not leave much room for a full answer.
Your question is very unclear so it is likely to be closed. Certainly, I do not see how anyone could answer it. That is why it is important that you try to solve your own problem and return as necessary with specific questions.
Below I provide links to recent posts that I believe will help you get started. As I said in my comment, look through recent posts. Use the search facility. There are some very good answers here if you look for them.
The first two posts are tutorials written by me. The early steps are the same but, because the questions were not quite the same, later steps are different. Look at both and pick out the bits relevant to you. The others posts all contain information you may find helpful.
How to import the outlook mail data to excel
update excel sheet based on outlook mail
could anyone guide me in creating an outlook macro that does the following
send an email from excel 2007 vba using an outlook template set variables
using visual basic to access subfolder in inbox
vba outlook event moving email
New section in response to new information from questioner
Except for minor modifications, the code in your question was taken from the Microsoft Help file for NewMailEx Event. This code will only work if you have the correct type of installation and if you place it in the correct place:
"The NewMailEx event will only fire for mailboxes in Microsoft Outlook that provide notification for received message such as Microsoft Exchange Server. Also, the event will fire only if Outlook is running. In other words, it will not fire for the new items that are received in the Inbox when Outlook was not open. Developers who want to access these items for customers running Outlook on an Exchange server e-mail account need to implement their code on the server. However, the NewMailEx event will fire against Cached Exchange Mode in all settings: Download Full Items, Download Headers, and Download Headers and then Full Items."
Do you have the correct type of installation? Can you place your code on the server? Even if this is the correct approach for the final version of your macro, I do not believe it is the correct approach while you are learning VBA and Outlook.
You need two things:
a detailed specification of the macro you wish to write and
more understanding of VBA and Outlook.
I doubt you can create the detailed specification yet because you do not know enough about VBA and Outlook. But we can list things you will need to know:
How do you write to your database from Outlook?
How do you identify the mail items you wish to record? In your example, you are checking for a subject of "Hello" and replying "Hi". This is fine for a first experiment but you need to identify the real method. Is it a new sender? Is there specific information in the body of the message? Does a human have to identify such mail items?
In your example, you have a folder "Personal" under "Inbox". Many people seem to have this type of folder structure and Microsoft examples tend to use folders like this. I do not. I have a folder called "!Home". Under this I have folders for "Insurance", "Shopping", "Money". Under these I have folders for my different suppliers. Once I have dealt with a message, I move it to appropriate folder. Replies go to the same folder. This is my system and it works for me. What is your system going to be? Will, for example, there be a single folder for all customers or one per customer?
The above is a starter list of questions for your specification but it is also a starter list of things you need to know.
Perhaps you have a boss who wants you to stop wasting time and start writing the macro but you do not know enough yet to plan the final macro.
Start with my tutorials. The first three steps are about the folder structure. These steps are essential if you have the kind of complex folder structures I have. Next I go through a folder displaying selected information from each mail item. I have steps in which I write message bodies to disc. I suggest you go through both tutorials and try my code. Not all of it will be immediately useful but it is all good background information.
What is your database? Is it Access or Excel? There is some help in my tutorials and in the other links above with writing to Excel which you could adapt for Access.
I think the above is enough for now. Take it slowly and it will start to make sense. I still remember the first time I tried to write an Outlook macro so I understand your confusion. I promise that it will become clear. Best of luck.
New section in response to the following comment:
"hello i have tried ..Got what i want....Removed my previous code..and tried replaced the new code .. Now little help needed from you ....is there any way to use same format like when we click the replyall button in outlook .. my code working fine ..prob is format of the mail is differ .."
Problem 1
.Body = .Body & Chr(13) & Chr(13)
You are using the text body. I think you want the HTML body. Try:
.HTMLBody = .HTMLBody & Chr(13) & Chr(13)
Problem 2
You cannot add to the HTML body in this way. The HTML body will be:
<!doctype ...><html><head> ... </head><body> ... </body></html>
You must add your text to the beginning of the body; that is, just after <body>. If you just add your text, you will be accepting whatever style, margins and colours the sender has used. The following code adds some text that looks the same in every email I have tried it with. My text is within a table with a single cell. The table covers the full width of the page. The text is blue on a white background.
Dim InsertStg As String
Dim Inx As Long
Dim Pos As Long
'Change the body step 1: Create the string to be inserted
InsertStg = "<table border=0 width=""100%"" style=""Color: #0000FF""" & _
" bgColor=#FFFFFF><tr><td><p>"
For Inx = 1 To 10
InsertStg = InsertStg & "Sentence " & Inx & " of first paragraph. "
Next
InsertStg = InsertStg & "</p><p>"
For Inx = 1 To 10
InsertStg = InsertStg & "Sentence " & Inx & " of second paragraph. "
Next
' The following adds a signature at the bottom of the message.
' "font-family" gives a list of fonts to be tried. If these are
' missing from your computer, use the names of fonts you do have.
' "serif" means that if none of the fonts exist any serif font
' that exists is to be used.
InsertStg = InsertStg & "</p><p style = ""font-family: Mistral, " & _
"Vivaldi, serif; font-size: 14px; color: " & _
"rgb(127,0,127)"">John Smith<br>5 Acacia Avenue<br>"
InsertStg = InsertStg & "</p></td></tr></table>"
'Change the body step 2: Find insertion position just after <Body> element
Pos = InStr(1, LCase(.HTMLBody), "<body")
If Pos = 0 Then
Call MsgBox("<Body> element not found in HTML body", vbCritical)
Exit Sub
End If
Pos = InStr(Pos, .HTMLBody, ">")
If Pos = 0 Then
Call MsgBox("Terminating > for <Body> element not found in HTML body", vbCritical)
Exit Sub
End If
'Change the body step 3: Insert my text into body
.HTMLBody = Mid(.HTMLBody, 1, Pos) & InsertStg & Mid(.HTMLBody, Pos + 1)

Script to create a follow up action on an email message in Outlook

I get two messages everday. The second message must arrive within 3.5 hours; if not, I have to start figuring out what went wrong with the second process that kept that email from getting sent.
Here's what I'd like to see happen.
Message one arrives
A rule executes and flags the message for follow-up (or anything really) 3.5 hours from that time.
There's a "run script" option in Outlook's Rules Wizard that I would use to trigger the script.
Bonus Points:
3 . When the second email arrives, it clears the follow-up flag from the first message.
Here's what I did:
Sub MyRule(Item As Outlook.MailItem)
MsgBox "Mail one has arrived: " & Item.Subject
Dim newMail As Outlook.MailItem
Set newMail = Outlook.CreateItem(olMailItem)
newMail.To = Item.To
newMail.Subject = "!!!Start looking for issues!!!!"
newMail.Body = "Something might have gone wrong with the process.. You did not receive any closing mail for " + Item.Subject + " received on " + Item.ReceivedTime
newMail.DeferredDeliveryTime = DateAdd("h", 3.5, Now)
newMail.Send
End Sub
This mail sits in your outbox for 3.5 hours and then gets sent.
This works only if you keep outlook running about 3.5 hours after the first mail. Till then when you try to close outlook, it will say that there are items in the outbox which are not sent. You can safely ignore this warning, but make sure that you have Outlook running afterwards.
(some of the code was written and tested in Outlook. but the body and subject part i have typed outside the VB Editor. You might have to resolve minor errors.)
EDIT:: for Bonus points..
Sub MyRuleForMessageTwo(Item As Outlook.MailItem)
Dim myitem As Outlook.MailItem
Set OutboxItems = Application.Session.GetDefaultFolder(olFolderOutbox).Items
Set myitem = OutboxItems.GetFirst
Do While Not (myitem Is Nothing)
If myitem.Subject = "!!!Start looking for issues!!!!" Then
myitem.Delete
Exit Do
End If
Set myitem = OutboxItems.GetNext
Loop
End Sub
You can play around with the matching criteria if you expect more than one message to be sitting in your outbox and you want to delete only one.
First of all, it sounds like you are creating a bizarre Rube Goldberg contraption, but that's going to be your problem, not mine, so have fun!
The way I would do this is to write a simple script that iterates through all messages in the inbox. Set the script to run every five minutes or so.
When it finds the first message of a pair, it records the time that message arrived. If it finds the second message, it checks to make sure that it arrived within 3.5 hours. If it doesn't find the second message, it checks if 3.5 hours have elapsed and warns you if they have.
There is no need to set flags on the first message. This doesn't get you any additional information that your script can't figure out later.