Jump to content

Outlook - find if status mail has being emailed out at the correct time


Recommended Posts

Hi There,

I'm a total beginner with AutoIT, but I like it, managed to make a script that hit's enter on an annoying pop-up everytime it appears, exported the script to an exe and now I think I'm a developer :)

 

I was just wondering if this new task was even possible to handle by AutoIT. We receive an email twice a day, 8:30 in the morning and 5 in the evening. Would I be able to script something, that woke up and scanned the inbox at 8:35 and 5:05 and checked the inbox if that status email was present (maybe checking for the mail subject which would always be the same) and if it didn't find the email issued in the last 5 minutes, it would email a user with a warning(report machine has fallen over). This would be running on a win10 machine with Outlook 365 cached locally.

 

Thanks

Link to comment
Share on other sites

Hello Mr developer :D,

yeah you can watch water's outlook UDF in my signature. 

Also, if you do research on my activity in the forum you're going to find some code example of what I did very recently in outlook. It totally fit to your needs.

I will edit and post some example code. But may you're going to be faster than me :).

#include <GuiComboBoxEx.au3>
#include <OutlookEX.au3>
#include <GUIConstants.au3>
#include <GUIConstantsEx.au3>
#include <MsgBoxConstants.au3>
#include <WindowsConstants.au3>
#include <GuiListView.au3>
#include <Array.au3>

_OL_ErrorNotify(2)

Global $oBoite = ""
Global $xInboxFolder = "\Inbox"
Global $xSubFolder = "\Test12345"

;~ $oBoite = "xxxxxxx@hotmail.com"
;~ $oBoite = "Contact@web-xxxx.com"

Global $oItem , $oOutlook , $aFolder , $oStoreID , $aItems , $EntryID
Global $nMsg , $cHeight , $iRow , $aResult , $aFolder2 , $aItems2 , $aItems3


$oOutlook = _OL_Open()
    If @error <> 0 Then Exit MsgBox(16, "Outlook", "Erreur de connection à Outlook. @error = " & @error & ", @extended: " & @extended)


$aFolder = _OL_FolderAccess($oOutlook, $oBoite, $olFolderInbox)
    If @error <> 0 Then Exit MsgBox(16, "Outlook", "Erreur de connection aux dossiers Outlook. @error = " & @error & ", @extended: " & @extended)
_ArrayDisplay ($aFolder , "$aFolder")

$aItems = _OL_ItemFind($oOutlook, $oBoite&$xInboxFolder , $olMail, "" , "", "", "SenderEmailAddress,SenderName,Subject,Body,EntryID,Categories", "[ReceivedTime], True", 0 )
    If @error <> 0 Then Exit MsgBox(16, "Outlook", "Erreur de connection aux items Outlook $aItems. @error = " & @error & ", @extended: " & @extended)
_ArrayDisplay ($aItems, "$aItems")

$aResult = _OL_FolderTree($oOutlook, $oBoite )
    If @error <> 0 Then Exit MsgBox(16, "Outlook", "Erreur d'arbo. @error = " & @error & ", @extended: " & @extended)
_ArrayDisplay ($aResult, "$aResult")

$aFolder2 = _OL_FolderFind( $oOutlook , $oBoite&$xInboxFolder , 99 , "Test12345" )
    If @error <> 0 Then Exit MsgBox(16, "Outlook", "Erreur Dossier introuvable folderfind. @error = " & @error & ", @extended: " & @extended)
_ArrayDisplay ( $aFolder2, "$aFolder2")

$aItems2 = _OL_ItemFind($oOutlook, $oBoite&"\Inbox\Test12345" , $olMail, "" , "", "", "SenderEmailAddress,SenderName,Subject,Body,EntryID,Categories", "[ReceivedTime], True", 0 )
    If @error <> 0 Then Exit MsgBox(16, "Outlook", "Erreur de connection aux items Outlook $aItems2. @error = " & @error & ", @extended: " & @extended)
_ArrayDisplay ($aItems2, "$aItems2")

$aItems3 = _OL_ItemFind($oOutlook, $oBoite&"\Inbox\Test12345" , $olMail , "", "", "", "EntryID")
    If $aItems3[0][0] = 0 Then Exit MsgBox(16, "OutlookEX UDF: _OL_ItemMove Example Script", "Could not find a mail item in folder $oBoite&'\Inbox\Test12345'. @error = " & @error)
_OL_ItemMove($oOutlook, $aItems3[1][0], $aFolder[3], $oBoite&"\Inbox\Test54321" )
    If @error <> 0 Then Exit MsgBox(16, "OutlookEX UDF: _OL_ItemMove Example Script", "Error moving specified task. @error = " & @error)

 

Warning on this

Global $oBoite = ""

$aItems2 = $oBoite&"\Inbox\Test12345"

_OL_ItemMove

_OL_ItemMove will move an item from a folder if you correct all values so be aware of it before lunch the script. 

If you comment that line then you can lunch without any modification

Edited by caramen

My video tutorials : ( In construction )  || My Discord : https://discord.gg/S9AnwHw

How to Ask Help ||  UIAutomation From Junkew || WebDriver From Danp2 || And Water's UDFs in the Quote

Spoiler

 Water's UDFs:
Active Directory (NEW 2018-10-19 - Version 1.4.10.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (2018-10-31 - Version 1.3.4.1) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
PowerPoint (2017-06-06 - Version 0.0.5.0) - Download - General Help & Support
Excel - Example Scripts - Wiki
Word - Wiki
 
Tutorials:

ADO - Wiki

 

Link to comment
Share on other sites

To get a script to launch at a specific time, the easiest solution is (imho) to set up a task in the Task Manager. You'll need to be an admin if you want it to log in and run the script. If you're not an admin, you can either have the task fail or start as soon as the user logs back in. Setting up the task should just be a one-time thing, unless you're trying to run this from multiple computers. If you are, take a look at water's Task Scheduler UDF (see a pattern? This guy is everywhere :D)

All my code provided is Public Domain... but it may not work. ;) Use it, change it, break it, whatever you want.

Spoiler

My Humble Contributions:
Personal Function Documentation - A personal HelpFile for your functions
Acro.au3 UDF - Automating Acrobat Pro
ToDo Finder - Find #ToDo: lines in your scripts
UI-SimpleWrappers UDF - Use UI Automation more Simply-er
KeePass UDF - Automate KeePass, a password manager
InputBoxes - Simple Input boxes for various variable types

Link to comment
Share on other sites

Thanks Guys, I'll get working on this now. Everyone has admin rights on their work computers so that's not a problem. It would be cool to have the program in stealth mode in the background watching the system clock and then spring only at a certain time. But you're right, I'll probably end up going that route as I'm as noob as it gets to this, and scripting in general.

Link to comment
Share on other sites

@seadoggie01's way is better for multiple reasons. 

But it totally depends on your end needs.

My video tutorials : ( In construction )  || My Discord : https://discord.gg/S9AnwHw

How to Ask Help ||  UIAutomation From Junkew || WebDriver From Danp2 || And Water's UDFs in the Quote

Spoiler

 Water's UDFs:
Active Directory (NEW 2018-10-19 - Version 1.4.10.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (2018-10-31 - Version 1.3.4.1) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
PowerPoint (2017-06-06 - Version 0.0.5.0) - Download - General Help & Support
Excel - Example Scripts - Wiki
Word - Wiki
 
Tutorials:

ADO - Wiki

 

Link to comment
Share on other sites

I have a pair of DOS batch scripts (one on each machine) which in turn launch a VB script, that are triggered twice daily, 11:00 and 23:00, by windows scheduler. The triggers are offset such that the emails arrive simultaneously in my gmail account, one says NB3 should be rebooting and the other says NB3 has just rebooted. I have been running these scripts for several years now and never get tired of deleting them as soon as they arrive in my inbox. On several occasions they have alerted me that NB3 has gone down. I did it this way as I had no need or desire to delve into the complexities of Outlook.

This is not an AutoIt solution but I thought I would throw it in the ring. It demonstrates how to send emails from your gmail account. I keep my little tools in C:\WinBin

My android devices all ping an audio alert whenever an email arrives and it gives me great satisfaction to hear them all go off at once around the house, much to the consternation of visitors.

 

:: With no args this will send an email "%COMPUTERNAME% reboot ok %date% %time%"
:: With -pre it will send a prealert email saying arg1 sb rebooting

@echo off
cd C:\WinBin
set To=YOUREMAIL@gmail.com
set Subj=%COMPUTERNAME% reboot ok %date% %time%
if .%1==.-pre set Subj=%2 sb rebooting %date% %time%
set Body=%Subj%
set From=YOUREMAIL@gmail.com
set Serv=smtp.gmail.com
set Auth=YOUREMAIL@gmail.com
set Pass=YOURPASSWORD
set fileattach=
call :createVBS email-bat.vbs
call :send %From% %To% "%Subj%" "%Body%" %Serv% %Auth% %Pass% 
echo email has been sent (if parameters were correct)
if exist email-bat.vbs del email-bat.vbs >nul
goto :EOF
exit

:send 
echo (echo) cscript.exe /nologo "%vbsfile%" %1 %2 %3 %4 %5 %6 %7 %8
cscript.exe /nologo "%vbsfile%" %1 %2 %3 %4 %5 %6 %7 %8
goto :EOF 

:createVBS
set "vbsfile=%~1"
if exist "%vbsfile%" del "%vbsfile%" >nul
set cdoSchema=http://schemas.microsoft.com/cdo/configuration
echo > "%vbsfile%" Set objArgs       = WScript.Arguments
echo >>"%vbsfile%" Set objEmail      = CreateObject("CDO.Message")
echo >>"%vbsfile%" objEmail.From     = objArgs(0)
echo >>"%vbsfile%" objEmail.To       = objArgs(1)
echo >>"%vbsfile%" objEmail.Subject  = objArgs(2)
echo >>"%vbsfile%" objEmail.Textbody = objArgs(3)
if defined fileattach echo >>"%vbsfile%" objEmail.AddAttachment "%fileattach%"
echo >>"%vbsfile%" with objEmail.Configuration.Fields
echo >>"%vbsfile%"  .Item ("%cdoSchema%/sendusing")        = 2 ' not local, smtp
echo >>"%vbsfile%"  .Item ("%cdoSchema%/smtpserver")       = objArgs(4)
:: 465 for Gmail. Other values for other servers.
echo >>"%vbsfile%"  .Item ("%cdoSchema%/smtpserverport")   = 465
echo >>"%vbsfile%"  .Item ("%cdoSchema%/smtpauthenticate") = 1 ' cdobasic
echo >>"%vbsfile%"  .Item ("%cdoSchema%/sendusername")     = objArgs(5)
echo >>"%vbsfile%"  .Item ("%cdoSchema%/sendpassword")     = objArgs(6)
:: True for Gmail, False for "other"
::echo >>"%vbsfile%"  .Item ("%cdoSchema%/smtpusessl")       = False
echo >>"%vbsfile%"  .Item ("%cdoSchema%/smtpusessl")       = True
echo >>"%vbsfile%"  .Item ("%cdoSchema%/smtpconnectiontimeout") = 25
echo >>"%vbsfile%"  .Update
echo >>"%vbsfile%" end with
echo >>"%vbsfile%" objEmail.Send
goto :EOF
exit

 

 

Edited by pseakins
Deleted irrelevant comments in code

Phil Seakins

Link to comment
Share on other sites

Ok so in short, at 8h30 am and 5 pm

You got 2 *.bat execute by windows scheduler that automated this :

If you don't receive an email then machine has fallen over and you email someone. 

Or if you have an email from a user which will remain permanent then you do nothing.

Anyway, with outlook UDF you can do that. To make your script easier to do. If you could make a server rule into this account to send that email if it comes in a special folder just for this then it will be very easy. 

If you can't make the rule then you could check the sender name or specific address/subject in the inbox (or whatever) and if it's present acting as you want. All in one script.

 

If you try something that does not work I will be glad to help you. As everyone else here ;). Give it a shot.

-You go to Outlook UDF page. 

-You download and read/try examples. 

-You have to check in help file for #include

-You check my script above. (Deleting the item move line) and then you replace "" by "youremail@xxx.com" And you try my script most are already here :).

-You read about If...Then...EndIf in help file too. 

-You decide :

__You make some new lines to send your mail (With outlook UDF)

__or you start your *.bat from the AutoIT script too. (With AutoIT native function : Run &/or ShellExecute)

Edited by caramen

My video tutorials : ( In construction )  || My Discord : https://discord.gg/S9AnwHw

How to Ask Help ||  UIAutomation From Junkew || WebDriver From Danp2 || And Water's UDFs in the Quote

Spoiler

 Water's UDFs:
Active Directory (NEW 2018-10-19 - Version 1.4.10.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (2018-10-31 - Version 1.3.4.1) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
PowerPoint (2017-06-06 - Version 0.0.5.0) - Download - General Help & Support
Excel - Example Scripts - Wiki
Word - Wiki
 
Tutorials:

ADO - Wiki

 

Link to comment
Share on other sites

Thanks @caramen  , I have being robbing example code and piecing it together, something a developer would never do 😜

I have the script popping up messages, when it sees a mail with the correct 'subject' arrive...so that's working. I intend, to trigger this with a scheduled task, and then this script will run with a timer for 5 minutes watching the new mails arrive, and then quit. If it doesn't see the mail with that subject in that timeframe it will email the boss.

I just pasted the 'send email code' into the thing now, so it's messier...Give me a little time to try and work this out...the test environment is not creating at the moment.

 

#AutoIt3Wrapper_Au3Check_Parameters= -d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6
#AutoIt3Wrapper_Au3Check_Stop_OnWarning=Y
#include <OutlookEX.au3>


; *****************************************************************************
; Create test environment (For sending the email)
; *****************************************************************************
Global $oOutlook = _OL_Open()
If @error <> 0 Then Exit MsgBox(16, "OutlookEX UDF", "Error creating a connection to Outlook. @error = " & @error & ", @extended = " & @extended)
Global $Result = _OL_TestEnvironmentCreate($oOutlook)
If @error <> 0 Then Exit MsgBox(16, "OutlookEX UDF - Manage Test Environment", "Error creating the test environment. @error = " & @error)


; *****************************************************************************
; Example Script
; Handle Outlook NewmailEX event when a new mail arrives.
; This script loops until Shift-Alt-E is pressed to exit.
; *****************************************************************************
HotKeySet("+!e", "_Exit") ;Shift-Alt-E to Exit the script
MsgBox(64, "OutlookEX UDF Example Script", "Hotkey to exit the script: 'Shift-Alt-E'!")

Global $oOApp = ObjCreate("Outlook.Application")
Global $test = ObjEvent($oOApp, "oOApp_")

While 1
    Sleep(10)
WEnd

; Outlook 2007 - NewMailEx event - http://msdn.microsoft.com/en-us/library/bb147646%28v=office.12%29.aspx
Func oOApp_NewMailEx($sOL_EntryId)

    Local $oOL_Item = $oOApp.Session.GetItemFromID($sOL_EntryId, Default)
    if $oOL_Item.Subject = "Today's International Red Alert Report" then
    MsgBox(64, "OutlookEX UDF Example Script", "New mail has arrived!" & @CRLF & @CRLF & _
            "From:    " & $oOL_Item.SenderName & @CRLF & _
            "Subject: " & $oOL_Item.Subject)

;*****************************************************************************
; Example 1
; Send a mail item
; *****************************************************************************
Global $aOL_Item = _OL_ItemFind($oOutlook, "*\Outlook-UDF-Test\SourceFolder\Mail", $olMail, "", "", "", "EntryID")
If $aOL_Item[0][0] = 0 Then Exit MsgBox(16, "OutlookEX UDF: _OL_ItemSend Example Script", "Could not find a mail item in folder 'Outlook-UDF-Test\SourceFolder\Mail'. @error = " & @error)
$Result = _OL_ItemSend($oOutlook, $aOL_Item[1][0])
If @error <> 0 Then Exit MsgBox(16, "OutlookEX UDF: _OL_ItemSend Example Script", "Error sending mail from folder 'Outlook-UDF-Test\SourceFolder\Mail'. @error = " & @error)

MsgBox(64, "OutlookEX UDF: _OL_ItemSend Example Script", "Mail successfully sent!")

_OL_Close($oOutlook)

      EndIf
EndFunc   ;==>oOApp_NewMailEx

Func _Exit()
    Exit
EndFunc   ;==>_Exit

 

Link to comment
Share on other sites

I recommend you to test on your own email in a test folder like I did. 

It will make things easier because if your reproducer is a success you won't have to re-code for the final script.

The only thing that will change are test environment value. 

Something like a sub folder into your inbox name it as you want. 

And try to work inside this folder only. 

Be aware of one thing. 

The function you are using will be available only if you have the script executed on the computer. That mean you don't need to task schedule. 

But just you have to keep that in mind. 

 

Another way is to use the OL item find. At any moment. But this way is good too. 

My video tutorials : ( In construction )  || My Discord : https://discord.gg/S9AnwHw

How to Ask Help ||  UIAutomation From Junkew || WebDriver From Danp2 || And Water's UDFs in the Quote

Spoiler

 Water's UDFs:
Active Directory (NEW 2018-10-19 - Version 1.4.10.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (2018-10-31 - Version 1.3.4.1) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
PowerPoint (2017-06-06 - Version 0.0.5.0) - Download - General Help & Support
Excel - Example Scripts - Wiki
Word - Wiki
 
Tutorials:

ADO - Wiki

 

Link to comment
Share on other sites

I recommend you to test on your own email in a test folder like I did. 

It will make things easier because if your reproducer is a success you won't have to re-code for the final script.

The only thing that will change are test environment value. 

Something like a sub folder into your inbox name it as you want. 

And try to work inside this folder only. 

Be aware of one thing. 

The function you are using will be available only if you have the script executed on the computer. That mean you don't need to task schedule. 

But just you have to keep that in mind. 

 

Another way is to use the OL item find. At any moment. But this way is good too. 

 

No sub folder into the search

$aItems2 = _OL_ItemFind($oOutlook, $oBoite&"\Inbox\Test12345" , $olMail, "" , "", "", "SenderEmailAddress,SenderName,Subject,Body,EntryID,Categories", "[ReceivedTime], True", 0 )

Sub folder included : 

$aItems2 = _OL_ItemFind($oOutlook, $oBoite&"\Inbox\Test12345" , $olMail, "" , "", "", "SenderEmailAddress,SenderName,Subject,Body,EntryID,Categories", "[ReceivedTime], True", 1 )

Check out parameter 2 inside these lines too

$oBoite = "" = the email account you want to target. 

It's concatened with : & 

and the rest of the folder name: "\Inbox\Test12345"

 

You could change everything to your test folder. You put some mails into this folder else you're going to get error and leave the script in this used example. 

If @error <> 0 Then Exit

 

Edited by caramen

My video tutorials : ( In construction )  || My Discord : https://discord.gg/S9AnwHw

How to Ask Help ||  UIAutomation From Junkew || WebDriver From Danp2 || And Water's UDFs in the Quote

Spoiler

 Water's UDFs:
Active Directory (NEW 2018-10-19 - Version 1.4.10.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (2018-10-31 - Version 1.3.4.1) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
PowerPoint (2017-06-06 - Version 0.0.5.0) - Download - General Help & Support
Excel - Example Scripts - Wiki
Word - Wiki
 
Tutorials:

ADO - Wiki

 

Link to comment
Share on other sites

sorry in my above code, I was using the wrong script, that script was for sending an existing mail item..... what I wanted to do was send a new mail to the boss in case the red alert email did not arrive on time.

@caramen  Thanks again, but don't underestimate how easily you can lose me,  I'll read through your replies very slowly shortly to see if I can make sense of them. I'm a total noob, I'll keep them in a folder like you said, I was thinking the task scheduler was needed to run this script at two times during the day even on the local machine.

 

I put this send wrapper code in, but it fails to send an email... Get a @error=5004  message which google tells me is something to do with credentials

anyway, I'll hack away at this a bit more.

 

#AutoIt3Wrapper_Au3Check_Parameters= -d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6
#AutoIt3Wrapper_Au3Check_Stop_OnWarning=Y
#include <OutlookEX.au3>

; *****************************************************************************
; Example Script
; Handle Outlook NewmailEX event when a new mail arrives.
; This script loops until Shift-Alt-E is pressed to exit.
; *****************************************************************************
HotKeySet("+!e", "_Exit") ;Shift-Alt-E to Exit the script
MsgBox(64, "OutlookEX UDF Example Script", "Hotkey to exit the script: 'Shift-Alt-E'!")

Global $oOApp = ObjCreate("Outlook.Application")
Global $test = ObjEvent($oOApp, "oOApp_")

; *****************************************************************************
; Connect to Outlook
; *****************************************************************************
Global $oOutlook = _OL_Open()
If @error <> 0 Then Exit MsgBox(16, "OutlookEX UDF", "Error creating a connection to Outlook. @error = " & @error & ", @extended = " & @extended)



While 1
    Sleep(10)
WEnd

; Outlook 2007 - NewMailEx event - http://msdn.microsoft.com/en-us/library/bb147646%28v=office.12%29.aspx
Func oOApp_NewMailEx($sOL_EntryId)

    Local $oOL_Item = $oOApp.Session.GetItemFromID($sOL_EntryId, Default)
    if $oOL_Item.Subject = "Today's International Red Alert Report" then
    MsgBox(64, "OutlookEX UDF Example Script", "New mail has arrived!" & @CRLF & @CRLF & _
            "From:    " & $oOL_Item.SenderName & @CRLF & _
            "Subject: " & $oOL_Item.Subject)


; *****************************************************************************
; Example 1
; Send a html mail to the current user.
; Add an attachment and set importance to high.
; *****************************************************************************
Global $sCurrentUser = $oOutlook.GetNameSpace("MAPI").CurrentUser.Name
_OL_Wrapper_SendMail($oOutlook, $sCurrentUser, "", "", "TestSubject", "Body<br><b>fett</b> normal.", @ScriptDir & "\_OL_Wrapper_SendMail.au3", $olFormatHTML, $olImportanceHigh)
If @error <> 0 Then Exit MsgBox(16, "OutlookEX UDF: _OutlookSendMail Wrapper Script", "Error sending mail. @error = " & @error & ", @extended: " & @extended)
MsgBox(64, "OutlookEX UDF: _OutlookSendMail Wrapper Script", "Mail successfully sent to user '" & $sCurrentUser & "'!")

_OL_Close($oOutlook)

      EndIf
EndFunc   ;==>oOApp_NewMailEx

Func _Exit()
    Exit
EndFunc   ;==>_Exit

 

Link to comment
Share on other sites

Replace $oOutlook with $oOApp in your script. The Outlook object is named $oOL in this example.

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2024-07-28 - Version 1.6.3.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
OutlookEX (2021-11-16 - Version 1.7.0.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (2021-04-13 - Version 1.4.0.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
PowerPoint (2021-08-31 - Version 1.5.0.0) - Download - General Help & Support - Example Scripts - Wiki
Task Scheduler (2022-07-28 - Version 1.6.0.1) - Download - General Help & Support - Wiki

Standard UDFs:
Excel - Example Scripts - Wiki
Word - Wiki

Tutorials:
ADO - Wiki
WebDriver - Wiki

 

Link to comment
Share on other sites

To make things easier for you if you want to try the lines I gave you 

First you setup your test environment (you don't need this for the last code you provided) 

You create a folder into your mailbox : to use my code example create one called: Test12345

image.png.330f7e9984ba092566493a9e070a6581.png

After that

You fix your code. 

First follow what water say just above. And you try it with F5 into SciTE editor. If you got error please past us the result from this area :

image.thumb.png.21acbd710e7d072c908115b7e138a247.png

Each time you press F5 into SciTE editor it will run the code and then if you got error inside your code it will be wrote into this field. 

 

Then if you got no error running this script. You can try to email yourself with subject : "Today's International Red Alert Report"

Also in good practice you have to change the position of this

Global $sCurrentUser

You should replace the way you declare this variable global. 

Add at the line 15 :

Global $sCurrentUser

And remove at line 43 or 44 depending on if you already made the first modification the Global word. You should never declare a global variable into a function. 

Try to get goo indentation in your code so it does not break your mind when you read your code too

this

#AutoIt3Wrapper_Au3Check_Parameters= -d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6
#AutoIt3Wrapper_Au3Check_Stop_OnWarning=Y
#include <OutlookEX.au3>

HotKeySet("+!e", "_Exit") ;Shift-Alt-E to Exit the script
MsgBox(64, "OutlookEX UDF Example Script", "Hotkey to exit the script: 'Shift-Alt-E'!")

Global $oOApp = ObjCreate("Outlook.Application")
Global $test = ObjEvent($oOApp, "oOApp_")
Global $oOutlook = _OL_Open()

If @error <> 0 Then Exit MsgBox(16, _
                                "OutlookEX UDF", _
                                "Error creating a connection to Outlook. @error = " & @error & ", @extended = " & @extended)

While 1
    Sleep(10)
WEnd

Func oOApp_NewMailEx($sOL_EntryId)
    Local $oOL_Item = $oOApp.Session.GetItemFromID($sOL_EntryId, Default)
        If $oOL_Item.Subject = "Today's International Red Alert Report" then
            MsgBox(64, "OutlookEX UDF Example Script", "New mail has arrived!" & @CRLF & @CRLF & _
                    "From:    " & $oOL_Item.SenderName & @CRLF & _
                    "Subject: " & $oOL_Item.Subject)
            Global $sCurrentUser = $oOutlook.GetNameSpace("MAPI").CurrentUser.Name
                        _OL_Wrapper_SendMail($oOutlook, _
                                    $sCurrentUser, _
                                    "", _
                                    "", _
                                    "TestSubject", _
                                    "Body<br><b>fett</b> normal.", _ 
                                    @ScriptDir & "\_OL_Wrapper_SendMail.au3", _ 
                                    $olFormatHTML, _ 
                                    $olImportanceHigh)
                If @error <> 0 Then Exit MsgBox(16, _ 
                                                "OutlookEX UDF: _OutlookSendMail Wrapper Script", _ 
                                                "Error sending mail. @error = " & @error & ", @extended: " & @extended)
            MsgBox(64, _ 
                    "OutlookEX UDF: _OutlookSendMail Wrapper Script", _ 
                    "Mail successfully sent to user '" & $sCurrentUser & "'!")
            _OL_Close($oOutlook)
        EndIf
EndFunc   ;==>oOApp_NewMailEx

Func _Exit()
    Exit
EndFunc   ;==>_Exit

Is better than the precedent one. 

A last hint for that snippet if I would be you I would change the place of line _OL_Close($oOutlook) just before the Exit into the _Exit function. 

Or this code will run only one time. And it's not really the expected behavior of : Func oOApp_NewMailEx which should run a verification on each mail. 

You could notice I'm not correcting for you so you start learning.

Edited by caramen

My video tutorials : ( In construction )  || My Discord : https://discord.gg/S9AnwHw

How to Ask Help ||  UIAutomation From Junkew || WebDriver From Danp2 || And Water's UDFs in the Quote

Spoiler

 Water's UDFs:
Active Directory (NEW 2018-10-19 - Version 1.4.10.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (2018-10-31 - Version 1.3.4.1) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
PowerPoint (2017-06-06 - Version 0.0.5.0) - Download - General Help & Support
Excel - Example Scripts - Wiki
Word - Wiki
 
Tutorials:

ADO - Wiki

 

Link to comment
Share on other sites

Here are my 2 cents worth:

  • The script needs to be started by the Task Scheduler.
  • It waits for n minutes for a mail with a specific subject. If this mail arrives the script ends.
  • If n minutes have passed the script ends as well. Sending an error message to another user can easily be implemented.
#AutoIt3Wrapper_Au3Check_Parameters= -d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6
#AutoIt3Wrapper_Au3Check_Stop_OnWarning=Y
#include <OutlookEX.au3>

; *****************************************************************************
; Handle Outlook NewmailEX event when a new mail arrives.
; This script waits for 5 minutes to make sure an expected mail has arrived
; in this time frame.
; *****************************************************************************
HotKeySet("+!e", "_Exit") ;Shift-Alt-E to Exit the script
MsgBox(64, "OutlookEX UDF Example Script", "Hotkey to exit the script: 'Shift-Alt-E'!")
; ------- Change the following lines to your liking
Global $sScriptName = "<Name of your script goes here>"
Global $sSubject = "<Subject of your expected mail>"
Global $iWaittime = 5           ; Duration in minutes of the window we will wait for the expected mail
; ------- End
Global $sStartTime = _NowCalc() ; Start (date/time) of the window we will wait for the expected mail
Global $bFound = False          ; Mail has not been found so far
AdlibRegister(_CheckTime, 10000) ; Check expiration of $iWaittime every 10 seconds
Global $oOutlook = _OL_Open()   ; Connect to Outlook
If @error <> 0 Then Exit MsgBox(16, $sScriptName, "Error creating a connection to Outlook. @error = " & @error & ", @extended = " & @extended)
Global $test = ObjEvent($oOutlook, "oOApp_")
Global $sCurrentUser = $oOutlook.GetNameSpace("MAPI").CurrentUser.Name
While 1
    Sleep(10)
WEnd

; Outlook 2007 - NewMailEx event - http://msdn.microsoft.com/en-us/library/bb147646%28v=office.12%29.aspx
Func oOApp_NewMailEx($sEntryIDs)
    Local $iItemCount, $oItem, $aEntryIDs = StringSplit($sEntryIDs, ",", $STR_NOCOUNT)
    $iItemCount = UBound($aEntryIDs)
    For $i = 0 To $iItemCount - 1
        $oItem = $oOutlook.Session.GetItemFromID($aEntryIDs[$i], Default)
        If $oItem.Subject = $sSubject Then 
            $bFound = True
            _Exit() ; Mail with correct subject arrived in the time window => Exit script
        EndIf
    Next
EndFunc   ;==>oOApp_NewMailEx

Func _Exit()
    If $bFound = False Then
        ; .... Send error mail to recipient
    EndIf
    _OL_Close($oOutlook)
    Exit
EndFunc   ;==>_Exit

Func _CheckTime()
    If _DateDiff("n", $sStartTime, _NowCalc()) >= $iWaittime Then _Exit()
EndFunc   ;==>_CheckTime

 

Edited by water
Grouped the lines to be changed by the user

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2024-07-28 - Version 1.6.3.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
OutlookEX (2021-11-16 - Version 1.7.0.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (2021-04-13 - Version 1.4.0.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
PowerPoint (2021-08-31 - Version 1.5.0.0) - Download - General Help & Support - Example Scripts - Wiki
Task Scheduler (2022-07-28 - Version 1.6.0.1) - Download - General Help & Support - Wiki

Standard UDFs:
Excel - Example Scripts - Wiki
Word - Wiki

Tutorials:
ADO - Wiki
WebDriver - Wiki

 

Link to comment
Share on other sites

9 hours ago, magnethead said:

I kind of wanted to experiment with AutoIT too, just to get a little more familiar with it. I've just found it and am very impressed with it

I discovered AutoIt over 10 years ago and have used it for all kinds of repetitive tasks. Until recently I was working for a major computer anti-virus organisation and we used my AutoIt tools as part of the distribution process of the virus signature database going out to millions of subscribers.

I can't recommend it enough and I really respect the tireless and patient support provided by the moderators of this forum. Some of the newbies ask moronic questions and/or expect code to be written for them without putting in any effort of their own. It's thankless work. Thank you @Jos in particular.

Phil Seakins

Link to comment
Share on other sites

Fairplay to both of you @caramen and @water ... Thats a beautiful looking piece of code. I won't be declaring my global parameters inside functions ever again.

and @water, that was a good trick....There was no error showing in the lower pane, it only took me 2 hours to correct that small piece of code  😜 or was it a mistype LOL

Quote

$iItemCount - 1

There was no error being thrown, but it would not detect mails with the correct subject.

It's working 100% now, and I love AutoIT all the more, I'm already thinking of another project....for messing with text files. Thanks again lads

 

#AutoIt3Wrapper_Au3Check_Parameters= -d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6
#AutoIt3Wrapper_Au3Check_Stop_OnWarning=Y
#include <OutlookEX.au3>

; *****************************************************************************
; Handle Outlook NewmailEX event when a new mail arrives.
; This script waits for 5 minutes to make sure an expected mail has arrived
; in this time frame.
; *****************************************************************************
HotKeySet("+!e", "_Exit") ;Shift-Alt-E to Exit the script
MsgBox(64, "OutlookEX UDF Example Script", "Hotkey to exit the script: 'Shift-Alt-E'!")

AdlibRegister(_CheckTime, 10000) ; Check expiration of $iWaittime every 10 seconds
Global $sScriptName = "Check for the IRA Email"
Global $sSubject = "Today's International Red Alert Report"
Global $sStartTime = _NowCalc() ; Start (date/time) of the window we will wait for the expected mail
Global $iWaittime = 1           ; Duration in minutes of the window we will wait for the expected mail
Global $bFound = False          ; Mail has not been found so far
Global $oOutlook = _OL_Open()   ; Connect to Outlook
If @error <> 0 Then Exit MsgBox(16, $sScriptName, "Error creating a connection to Outlook. @error = " & @error & ", @extended = " & @extended)
Global $test = ObjEvent($oOutlook, "oOApp_")
Global $sCurrentUser = $oOutlook.GetNameSpace("MAPI").CurrentUser.Name
While 1
    Sleep(10)
WEnd

; Outlook 2007 - NewMailEx event - http://msdn.microsoft.com/en-us/library/bb147646%28v=office.12%29.aspx

Func oOApp_NewMailEx($sEntryIDs)
    Local $iItemCount, $oItem, $aEntryIDs = StringSplit($sEntryIDs, ",", $STR_NOCOUNT)
    $iItemCount = UBound($aEntryIDs)
    For $i = 0 To $iItemCount = 1
        $oItem = $oOutlook.Session.GetItemFromID($aEntryIDs[$i], Default)
        If $oItem.Subject = $sSubject Then
            $bFound = True
            MsgBox(64, "OutlookEX UDF: _OutlookSendMail Wrapper Script", "Mail has arrived '" & $sCurrentUser & "'!")
            _Exit() ; Mail with correct subject arrived in the time window => Exit script
        EndIf
    Next
EndFunc   ;==>oOApp_NewMailEx

Func _Exit()
    If $bFound = False Then
        ; .... Send error mail to recipient
        _OL_Wrapper_SendMail($oOutlook, $sCurrentUser, "", "", "EMERGENCY --- RED ALERT DID NOT ISSUE", "Did you know<br><b>the IRA did not issue just now, Time to panic</b>","", $olFormatHTML, $olImportanceHigh)
If @error <> 0 Then Exit MsgBox(16, "OutlookEX UDF: _OutlookSendMail Wrapper Script", "Error sending mail. @error = " & @error & ", @extended: " & @extended)
MsgBox(64, "OutlookEX UDF: _OutlookSendMail Wrapper Script", "Mail successfully sent to user '" & $sCurrentUser & "'!")

    EndIf
    _OL_Close($oOutlook)
    Exit
EndFunc   ;==>_Exit

Func _CheckTime()
    If _DateDiff("n", $sStartTime, _NowCalc()) >= $iWaittime Then _Exit()
EndFunc   ;==>_CheckTime

 

Link to comment
Share on other sites

8 hours ago, magnethead said:

$iItemCount - 1

That's definitely correct. It processes an array starting with the first element. As the index starts with 0 you have to subtract 1.
e.g. Array with 5 elements. The index goes from 0 to 4. To get the highest index you grab the number of entries in the array and subtract 1.

Your current solution works by accident. If my solution does not work then there is another problem.

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2024-07-28 - Version 1.6.3.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
OutlookEX (2021-11-16 - Version 1.7.0.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (2021-04-13 - Version 1.4.0.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
PowerPoint (2021-08-31 - Version 1.5.0.0) - Download - General Help & Support - Example Scripts - Wiki
Task Scheduler (2022-07-28 - Version 1.6.0.1) - Download - General Help & Support - Wiki

Standard UDFs:
Excel - Example Scripts - Wiki
Word - Wiki

Tutorials:
ADO - Wiki
WebDriver - Wiki

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...