簡體   English   中英

使用 python imap 從 outlook 檢索附件文件(csv)

[英]Retrieve attachment file(csv) from outlook using python imap

我正在嘗試從 outlook 上的 email 檢索附件,並將該附件作為 csv 文件下載到我本地計算機上的路徑。

這是我從這里獲取的代碼示例

import imaplib
import base64
import os
import email
from datetime import datetime

mail = imaplib.IMAP4('outlook.office365.com',993)
mail.login('email','password')
mail.select('Inbox')

type, data = mail.search(None, 'ALL')
mail_ids = data[0]
id_list = mail_ids.split()

for num in data[0].split():
    typ, data = mail.fetch(b'1', '(RFC822)' )
    raw_email = data[0][1]
# converts byte literal to string removing b''
    raw_email_string = raw_email.decode('utf-8')
    email_message = email.message_from_string(raw_email_string)
# downloading attachments
    for part in email_message.walk():
        # this part comes from the snipped I don't understand yet... 
        if part.get_content_maintype() == 'multipart':
            continue
        if part.get('Content-Disposition') is None:
            continue
        fileName = part.get_filename()
        if bool(fileName):
            filePath = os.path.join(mypath, fileName)
            if not os.path.isfile(filePath) :
                fp = open(filePath, 'wb')
                fp.write(part.get_payload(decode=True))
                fp.close()
            subject = str(email_message).split("Subject: ", 1)[1].split("\nTo:", 1)[0]
             print('Downloaded "{file}" from email titled "{subject}" with UID {uid}.'.format(file=fileName, subject=subject, uid=latest_email_uid.decode('utf-8')))

但是我在執行這部分時一直出現“中止:套接字錯誤:EOF”的錯誤:

mail = imaplib.IMAP4('outlook.office365.com',993)
mail.login('email','password')
mail.select('Inbox')

所以在尋找堆棧上的這個錯誤時,我找到了另一種寫它的方法:

while True:
    mail = imaplib.IMAP4('outlook.office365.com',993)
    r, d = mail.login('email','password')
    assert r == 'OK', 'login failed'
    try:
        mail.select('Inbox')
    except imap.abort as e:
        continue
    imap.logout()
    break

但仍然有同樣的中止錯誤。

為了更好的實踐,我也試圖避免使用 while 語句。

誰能幫我嗎?

我正在嘗試使用 python 3> 從特定發件人登錄並下載文件,並使用 outlook 中的主題

提前致謝。

您需要使用 SSL。 您正在嘗試使用明文 session 連接到加密端口。

確保您使用的是 IMAP object 的 SSL 版本:

mail = imaplib.IMAP4_SSL('outlook.office365.com',993)

服務器關閉您的連接,因為它沒有收到 SSL 協商。

暫無
暫無

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

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