使用imaplib检索电子邮件正文

时间:2012-11-14 06:15:36

标签: python imaplib

我正在尝试确保从某个电子邮件地址检索所有正文(无论电子邮件的格式是什么)。在此示例(imaplib_connect)中省略了连接详细信息,因为所有这些似乎都有效,但我认为以下内容对于所有电子邮件正文都不够。任何改进建议?我正在将每个电子邮件的正文写入文件。

import imaplib
import imaplib_connect
import uuid
import ConfigParser
import os
import email

c = imaplib_connect.open_connection()
try:
    config = ConfigParser.ConfigParser()
    config.read([os.path.expanduser('~/reader.config')])
    fromAddress = config.get('account', 'fromAddress')
    typ, data = c.select('INBOX')
    typ, data = c.search(None, '(FROM "' + fromAddress + '")')
    print "Processing..."
    for num in data[0].split():
        typ, data = c.fetch(num, '(RFC822)')
        rawMessage = data[0][1]
        emailMessage = email.message_from_string(rawMessage)
        maintype = emailMessage.get_content_maintype()
        fileName = uuid.uuid4().hex
        if maintype == 'multipart':
             for part in emailMessage.get_payload():
                 if part.get_content_maintype() == 'text':
                    with open(fileName + ".txt", "wb") as fo:
                         fo.write(part.get_payload())
                 elif maintype == 'text':
                    with open(fileName + ".txt", "wb") as fo:
                         fo.write(part.get_payload())
finally:
    try:
        c.close()
    except:
        pass
    c.logout()

0 个答案:

没有答案