簡體   English   中英

如何使用 python 3.4 下載 Outlook 電子郵件附件

[英]How to download outlook email attachments using python 3.4

我正在嘗試使用 python 3.4 下載 Outlook 電子郵件附件,我已使用 Gmail 憑據登錄 Outlook。 我可以知道如何從 Outlook 中獲取附件嗎? 提前致謝

嘗試這個:

import email, imaplib
import os
class FetchEmail():
    def __init__(self,
        mail_server="outlook.office365.com", 
        username="username@outlook.com",
        password="'password'"):

        self.error = None
        self.connection = None
        self.mail_server = mail_server
        self.username = username
        self.password = password
        self.connection = imaplib.IMAP4_SSL(mail_server)
        self.connection.login(username, password)
        self.connection.select(readonly=False) # so we can mark mails as readread

    def close_connection(self):
          """
        Close the connection to the IMAP server
        """
          self.connection.close()

    def save_attachment(self, msg, download_folder="/tmp"):
        """
        Given a message, save its attachments to the specified
        download folder (default is /tmp)

        return: file path to attachment
        """
        att_path = "No attachment found."
        for part in msg.walk():
            if part.get_content_maintype() == 'multipart':
                continue
            if part.get('Content-Disposition') is None:
                continue

            filename = part.get_filename()
            att_path = os.path.join(download_folder, filename)

            if not os.path.isfile(att_path):
                fp = open(att_path, 'wb')
                fp.write(part.get_payload(decode=True))
                fp.close()
        return att_path

    def fetch_unread_messages(self):
        """
        Retrieve unread messages
        """
        emails = []
        (result, messages) = self.connection.search(None, 'UnSeen')
        if result == "OK":
            for message in messages[0].split(' '):
                try: 
                    ret, data = self.connection.fetch(message,'(RFC822)')
                except:
                    print ("No new emails to read.")
                    self.close_connection()
                    exit()

                msg = email.message_from_string(data[0][1])
                if isinstance(msg, str) == False:
                    emails.append(msg)
                response, data = self.connection.store(message, '+FLAGS','\\Seen')

            return emails

        self.error = "Failed to retreive emails."
        return emails


fe = FetchEmail()

您還可以看到這些: 如何在 python 中使用 imaplib 獲取電子郵件正文? 使用 imap 下載新電子郵件附件的 Python 腳本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM