【问题标题】:Download attachment from shared Outlook mailbox从共享的 Outlook 邮箱下载附件
【发布时间】:2018-08-18 02:35:34
【问题描述】:

这是我用来从我的收件箱下载具有特定主题的附件的代码。知道如何调整脚本以访问邮箱中的共享文件夹并从中下载附件吗?

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()

【问题讨论】:

    标签: python outlook


    【解决方案1】:

    假设您的服务器支持 EWS,请尝试改用 exchangelib

    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)
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-20
    • 2020-03-11
    • 1970-01-01
    相关资源
    最近更新 更多