简体   繁体   中英

Python: Downloading Outlook Attachments and Change Filename on Save

the following code works below, however i am trying to add a parameter that changes the filename on the SaveAsFile method to the iteration of (a) the message that i am on.

As an Example the Current output is

Returned mail see transcript for details
Returned mail see transcript for details

The Desired output is

Returned mail see transcript for details1
Returned mail see transcript for details2
Returned mail see transcript for details3

Currently this code just overwrites the same save file in my folder, however i need to accomplish saving that same file from different messages to a new file name.

Code Below:

import win32com.client
import os
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case the inbox. You can change that number to reference
messages = inbox.Items
message = messages.GetFirst()
subject = message.Subject
i = 0
#
get_path = r'S:\Corporate Shared\Contracting Shared\DATA_PROJECTS\James\Email Extraction\Undeliverable Items'

for m in messages:
    i = i + 1 #numeration
    a = str(i) #Creates i as a string
    if m.Subject == ("Returned mail: see transcript for details"):
        #print(message)
        attachments = message.Attachments
        num_attach = len([x for x in attachments])
        for x in range(1, num_attach + 1):
            attachment = attachments.Item(x)
            attachment.SaveASFile(os.path.join(get_path,attachment.FileName))
            print(attachment)
            #print(a)
        message = messages.GetNext()

    else:
        message = messages.GetNext()

Instead of using attachment.FileName in the call to os.path.join , store attachment.FileName in a variable, then replace the last "." with "_" + x + "."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM