-1

This is the code I used to download attachments with a certain subject from my Inbox. Any idea how to tweak the script to access a shared folder in the mailbox and download an attachment from it?

import imaplib
import email
import os

svdir = 'Directory to Save'


mail=imaplib.IMAP4('IMAP Server')
mail.login("UserName","Password")
mail.select("Inbox")

typ, msgs = mail.search(None, '(SUBJECT "Subject Of Mail")')
msgs = msgs[0].split()

for emailid in msgs:
    resp, data = mail.fetch(emailid, "(RFC822)")
    email_body = data[0][1] 
    m = email.message_from_string(email_body)


    if m.get_content_maintype() != 'multipart':
     continue

    for part in m.walk():
        if part.get_content_maintype() == 'multipart':
            continue
        if part.get('Content-Disposition') is None:
            continue

        filename=part.get_filename()
        if filename is not None:
            sv_path = os.path.join(svdir, filename)
            if not os.path.isfile(sv_path):
                print sv_path       
                fp = open(sv_path, 'wb')
                fp.write(part.get_payload(decode=True))
                fp.close()
Erik Cederstrand
  • 9,643
  • 8
  • 39
  • 63

1 Answers1

0

Assuming your server supports EWS, try using exchangelib instead:

from exchangelib import Account, Credentials, FileAttachment

a = Account(
    'some_other_user@example.com',
    credentials=Credentials('UserName', 'Password'), 
    autodiscover=True
)
msg = a.inbox.get(subject='Subject Of Mail')
for attachment in msg.attachments:
    if isinstance(attachment, FileAttachment):
        local_path = os.path.join('/tmp', attachment.name)
        with open(local_path, 'wb') as f:
            f.write(attachment.content)
Erik Cederstrand
  • 9,643
  • 8
  • 39
  • 63