October 27, 2024
Chicago 12, Melborne City, USA
python

Reading and downloading email attachments using win32com with one or more mail boxes


How can I add another mailbox to the below code?

import win32com.client
import os
from datetime import datetime, timedelta
outlook = win32com.client.Dispatch('outlook.application')
mapi = outlook.GetNamespace("MAPI")
target_account_name = "abc@abc.com.aa"
for account in mapi.Accounts:
    print(account.DeliveryStore.DisplayName) #outlook account
inbox = mapi.GetDefaultFolder(6) #Inbox folder
messages = inbox.Items 
received_dt = datetime.now() - timedelta(days=1)
email_subject="Base2"#outputDir="Z:\CLCM"
outputDir="N:\M_folder"
try:
    for message in list(messages):
        if email_subject in message.subject:
            try:
                s = message.sender
                for attachment in message.Attachments:
                    attachment.SaveASFile(os.path.join(outputDir, attachment.FileName))
                    print(f"attachment {attachment.FileName} from {s} saved")
            except Exception as e:
                print("Error when saving the attachment:" + str(e))
except Exception as e:
    print("Error when processing emails messages:" + str(e))

New to python!

I want to know how I can add another mailbox to the above code. It always selects the first account. How can I modify this to get all the accounts we have and then select the second?



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video