如何在不使用Python触及附件的情况下有效地解析电子邮件

Vie*_*iet 7 python gmail parsing imap imaplib

我正在使用Python imaplib(Python 2.6)来从GMail获取电子邮件.我用方法http://docs.python.org/library/imaplib.html#imaplib.IMAP4.fetch获取电子邮件的所有内容我收到完整的电子邮件.我只需要文本部分,也可以解析附件的名称,而无需下载它们.怎么做到这一点?我看到GMail返回的电子邮件遵循浏览器发送到HTTP服务器的相同格式.

swa*_*son 5

看看这个食谱: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
Run Code Online (Sandbox Code Playgroud)

这应该足以让你朝着正确的方向前进.


Jus*_*eel 0

恐怕你运气不好。根据这篇文章,电子邮件只有两个部分 - 标题和正文。正文是附件所在的位置(如果有的话),您必须在仅提取邮件文本之前下载整个正文。这里找到的关于 FETCH 命令的信息也支持这个观点。虽然它说您可以提取正文的部分内容,但这些是以八位位组指定的,这并没有真正的帮助。