如何使用Python高效解析不涉及附件的邮件
我正在使用Python的imaplib库(Python 2.6)来从GMail获取邮件。每次我用这个方法获取邮件时,都会拿到整封邮件。我只想要邮件的文本部分,并且想提取附件的名称,但不想下载这些附件。这该怎么做呢?我发现GMail返回的邮件格式和浏览器发送给HTTP服务器的格式是一样的。
3 个回答
2
你可以通过下面的方式只获取邮件的纯文本:
connection.fetch(id, '(BODY[1])')
在我看到的gmail邮件中,第一部分包含了纯文本内容,还有一些多部分的杂七杂八的东西。这种方法可能不太稳定。
我不知道怎么在不获取所有内容的情况下得到附件的名字。我还没有尝试使用部分内容。
5
看看这个食谱: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
这些信息应该能帮助你朝着正确的方向前进。