I've created a vbs to retrieve the attachments from Outlook unread emails and store them into a folder.
GetMail.vbs
Dim SavePath
Dim Subject
Dim FileExtension
Dim k
SavePath = "D:\IN\"
Subject = "'Replication IN'"
Set objOutlook = CreateObject("Outlook.Application")
Set objNamespace = objOutlook.GetNamespace("MAPI")
Set objFolder = objNamespace.GetDefaultFolder(6) 'Inbox
Set colItems = objFolder.Items
Set colFilteredItems = colItems.Restrict("[Unread]=true")
Set colFilteredItems = colFilteredItems.Restrict("[Subject] = " & Subject)
For k = colFilteredItems.Count to 1 step -1
set objMessage = colFilteredItems.Item(k)
intCount = objMessage.Attachments.Count
If intCount > 0 Then
For i = 1 To intCount
objMessage.Attachments.Item(i).SaveAsFile SavePath & _
objMessage.Attachments.Item(i).FileName
Next
objMessage.Unread = False
End If
Next
Now, I've to automatize this task and once done, execute another program which will process the received attachments. To do that, I've created a batch file.
MyBatch.bat
cls
@ECHO OFF
ECHO. * Retrieving emails ... *
"D:\GetMail.vbs"
ECHO. * Importing data. Please wait ... *
"D:\MyProgram.exe"
CLS
EXIT
I've no problems and everything works fine when executing the .bat file. But when this file is executed by a scheduled task the script is not able to read the emails neither collect the attachments.
I've checked the following:
What could be the cause?
Outlook, just like any other Office app, cannot be used in a service (that is what Task Scheduler is).
You can use Extended MAPI (C++ or Delphi only) or a wrapper such as Redemption (I am its author - any language), it's RDO family of objects can be used in a service.
You might also want to add a call to Namepace.Logon
:
Set objOutlook = CreateObject("Outlook.Application")
Set objNamespace = objOutlook.GetNamespace("MAPI")
objNamespace.Logon
Set objFolder = objNamespace.GetDefaultFolder(6) 'Inbox