Situation:
I receive an email with an attachment on a daily basis, but I don't want to have to save it manually all the time, so I've made a script to download it for me.
I'm using the Python library win32com to run Outlook in the background:
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
The script finds the latest email with an attachment and saves it.
Problem:
It doesn't save the latest attachment. It always stays at the same email, as if Outlook had not updated at all. The only time it works is if I delete my Outlook profile and I create a new one. Any ideas on what the reason for this behaviour is?
Regards,
Doyuno
CODE:
# -*- coding: utf-8 -*-
import datetime
import pandas as pd
import win32com.client
path = "C:\some\path"
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
def getfoldernum():
i = 1
for x in outlook.Folders:
if ('[email protected]' == str(x)):
print 'Found the Folder'
return i
else:
i += 1
def main():
foldernum = getfoldernum()
inbox = outlook.Folders.Item(foldernum).Folders('Inbox')
d = 0
w = 0
messages = inbox.Items
for msg in messages:
print msg.SentOn
if msg.Attachments:
attachments = msg.Attachments
for attachment in attachments:
if 'Attachment name' in str(attachment.FileName):
location = path + 'Archive\\Daily\\'+str(attachment.FileName)
attachment.SaveAsFile(location)
df = pd.read_excel(location)
if d == 0:
attachment.SaveAsFile(path+'filename.xlsx')
d = 1
else:
print 'Attachment not found or wrong name'
if __name__ == '__main__':
main()