1
votes

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()
1
Could you share more of your script, particularly the portion that "finds the latest email"?sgriffin
Please show the code that actually fails to do what you expect it to do.Dmitry Streblechenko
@DmitryStreblechenko, Updated above. The reason why I didn't show the code is that the code works fine on another Windows machine. The code is simple, downloads the latest email attachment that matches a string "Attachment name". If I create a new profile it updates with the latest email, but then it doesn't stay up to date.Doyuno Dawae
@sgriffin Updated aboveDoyuno Dawae

1 Answers

0
votes

Your script will act on whichever item happens to be first in the collection Items, and you haven’t done anything to specify how this collection should be sorted. So if the collection happens to be sorted with the most recent item first, your code happens to work. You should use Items.Sort to specify a sort order.