【问题标题】:How to efficiently parse emails without touching attachments using Python如何使用 Python 在不接触附件的情况下有效地解析电子邮件
【发布时间】:2011-01-19 01:29:54
【问题描述】:
【问题讨论】:
标签:
python
parsing
gmail
imap
imaplib
【解决方案1】:
看看这个食谱:http://code.activestate.com/recipes/498189/
我稍微调整了它以打印发件人、主题、日期、附件名称和邮件正文(现在只是纯文本 - 添加 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
这应该足以让您朝着正确的方向前进。
【解决方案2】:
您可以通过执行以下操作仅获取电子邮件的纯文本:
connection.fetch(id, '(BODY[1])')
对于我看到的 gmail 邮件,第 1 部分包含明文,包括多部分垃圾邮件。这可能不是那么健壮。
如果没有附件,我不知道如何获取附件的名称。我还没有尝试使用部分。
【解决方案3】:
恐怕你运气不好。根据this post,电子邮件只有两部分 - 标题和正文。正文是附件所在的位置(如果有),您必须在仅提取消息文本之前下载整个正文。找到的有关 FETCH 命令的信息here 也支持这一观点。虽然它说您可以提取正文的部分内容,但这些部分是根据八位字节指定的,这并没有真正的帮助。