问题描述
我正在使用Python imaplib(Python 2.6)来从GMail获取电子邮件。所有我用方法我收到整封电子邮件。我只需要文本部分,并解析附件的名称,而无需下载它们。如何做到这一点?我看到GMail返回的电子邮件遵循与浏览器发送给HTTP服务器相同的格式。
I'm playing with Python imaplib (Python 2.6) to fetch emails from GMail. Everything I fetch an email with method http://docs.python.org/library/imaplib.html#imaplib.IMAP4.fetch I get whole email. I need only text part and also parse names of attachments, without downloading them. How this can be done? I see that emails returned by GMail follow the same format that browsers send to HTTP servers.
推荐答案
看看这个配方:
我稍微调整它以打印From,Subject,Date,附件名称和邮件正文(现在只是明文 - 对于添加html邮件来说是微不足道的)。
I adapted it slightly to print the From, Subject, Date, name of attachments, and message body (just plaintext for now -- its trivial to add html messages).
在这种情况下,我使用了Gmail pop3服务器,但它也适用于IMAP。
I used the Gmail pop3 server in this case, but it should work for IMAP as well.
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
这应该足以让您朝着正确的方向前进。
This should be enough to get you heading in the right direction.
这篇关于如何高效地解析电子邮件,而无需使用Python触摸附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!