I wrote a python code to download email attachments and this code works fine when I start it manually (just double click/open with python).
However, when I tried setting up a task in task scheduler, the job keeps running forever and no output is seen (no attachments in the output folder). What have I done wrong here?
I tried all combination of scheduler settings I could think of (run only when user is logged on/ run whether or not user is logged on; run with highest privileges)
I also tried defining actions in different ways:
-script: C:\Windows\System32\cmd.exe
-argument: "C:\ProgramData\Anaconda3\python.exe "C:\Users\LN\Documents\PythonScripts\outlookdownload.py""
-script: C:\ProgramData\Anaconda3\python.exe
-argument: "C:\Users\LN\Documents\PythonScripts\outlookdownload.py"
-script: C:\ProgramData\Anaconda3\python.exe
-argument: "C:\Users\LN\Documents\PythonScripts\outlookdownload.py"
-start in: C:\Users\LN\Documents\PythonScripts\
-script: C:\ProgramData\Anaconda3\python.exe
-argument: "C:\Users\LN\Documents\PythonScripts\outlookdownload.py"
-start in: C:\Users\LN\Documents\PythonScripts\"
Below is the python code:
outpfolder= [output folder link]
import datetime
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.Folders('Elo Inventory').Folders('Inbox')
messages = inbox.Items
message = messages.GetLast()
sentdate = message.senton.date()
datelimit = (datetime.date.today () - datetime.timedelta (days=7))
#define function to save attachment:
def OL_Attsave(outpath, name, filenamefilter):
attachments = message.Attachments
att_count = attachments.Count
for i in range(1,att_count+1):
attachment = attachments.Item(i)
if filenamefilter in attachment.FileName and "image" not in attachment.FileName:
attachment.SaveASFile(outpath + str(sentdate)+"_"+name+"_" +str(attachment.Filename))
return "saved " + str(att_count) + " files for " + name +" to " + outpath
while sentdate>datelimit:
try:
#Company1:
if message.SenderEmailAddress == "abc@company1.com" and message.subject == "INV ELO":
outpath = outpfolder + "company1\\"
name = 'company1'
OL_Attsave(outpath, name ,'')
#Company2:
elif "@company2.com" in message.SenderEmailAddress:
outpath = outpfolder + "company2\\"
name = 'company2'
OL_Attsave(outpath, name, 'INV')
message = messages.GetPrevious()
sentdate = message.senton.date()
except:
message = messages.GetPrevious()
sentdate = message.senton.date()