簡體   English   中英

如何在不使用Python觸及附件的情況下有效地解析電子郵件

[英]How to efficiently parse emails without touching attachments using Python

我正在使用Python imaplib(Python 2.6)來從GMail獲取電子郵件。 我用方法http://docs.python.org/library/imaplib.html#imaplib.IMAP4.fetch獲取電子郵件的所有內容我收到完整的電子郵件。 我只需要文本部分,也可以解析附件的名稱,而無需下載它們。 怎么做到這一點? 我看到GMail返回的電子郵件遵循瀏覽器發送到HTTP服務器的相同格式。

看看這個食譜: http//code.activestate.com/recipes/498189/

我稍微調整了它以打印From,Subject,Date,附件名稱和消息正文(現在只是純文本 - 添加HTML消息很簡單)。

在這種情況下我使用了Gmail pop3服務器,但它也適用於IMAP。

import poplib, email, string

mailserver = poplib.POP3_SSL('pop.gmail.com')
mailserver.user('recent:YOURUSERNAME') #use 'recent mode'
mailserver.pass_('YOURPASSWORD') #consider not storing in plaintext!

numMessages = len(mailserver.list()[1])
for i in reversed(range(numMessages)):
    message = ""
    msg = mailserver.retr(i+1)
    str = string.join(msg[1], "\n")
    mail = email.message_from_string(str)

    message += "From: " + mail["From"] + "\n"
    message += "Subject: " + mail["Subject"] + "\n"
    message += "Date: " + mail["Date"] + "\n"

    for part in mail.walk():
        if part.is_multipart():
            continue
        if part.get_content_type() == 'text/plain':
            body = "\n" + part.get_payload() + "\n"
        dtypes = part.get_params(None, 'Content-Disposition')
        if not dtypes:
            if part.get_content_type() == 'text/plain':
                continue
            ctypes = part.get_params()
            if not ctypes:
                continue
            for key,val in ctypes:
                if key.lower() == 'name':
                    message += "Attachment:" + val + "\n"
                    break
            else:
                continue
        else:
            attachment,filename = None,None
            for key,val in dtypes:
                key = key.lower()
                if key == 'filename':
                    filename = val
                if key == 'attachment':
                    attachment = 1
            if not attachment:
                continue
            message += "Attachment:" + filename + "\n"
        if body:
            message += body + "\n"
    print message
    print

這應該足以讓你朝着正確的方向前進。

通過執行以下操作,您只能獲得電子郵件的純文本:

connection.fetch(id, '(BODY[1])')

對於我見過的gmail消息,第1節有明文,包括多部分垃圾。 這可能不那么強大。

我不知道如何在沒有全部的情況下獲得附件的名稱。 我沒有嘗試過使用partials。

我怕你運氣不好。 根據這篇文章 ,電子郵件只有兩個部分 - 標題和正文。 身體是附件所在的位置,如果有任何附件,則必須在僅提取消息文本之前下載整個身體。 此處找到的有關FETCH命令的信息也支持此觀點。 雖然它說你可以提取身體的部分,但是這些都是用八位字節來指定的,這並沒有真正幫助。

暫無
暫無

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

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