我正在使用 Python imaplib (Python 2.6) 从 GMail 获取电子邮件。我用方法获取电子邮件的所有内容http://docs.python.org/library/imaplib.html#imaplib.IMAP4.fetch我收到整封电子邮件。我只需要文本部分,还可以解析附件的名称,而无需下载它们。如何做到这一点?我发现 GMail 返回的电子邮件遵循浏览器发送到 HTTP 服务器的相同格式。
看看这个食谱: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
这应该足以让您朝着正确的方向前进。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)