我试图确保从某个电子邮件地址检索所有正文(无论电子邮件采用何种格式)。本示例中省略了连接详细信息(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()