如何使用python接收邮件 [英] How to receive mail using python

查看:142
本文介绍了如何使用python接收邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用python接收电子邮件。到目前为止,我已经能够得到这个主题而不是身体。以下是我一直在使用的代码:

  import poplib 
from email import parser
pop_conn = poplib .POP3_SSL('pop.gmail.com')
pop_conn.user('myusername')
pop_conn.pass _('mypassword')
#从服务器获取消息:
消息= [pop_conn.retr(i)for i in range(1,len(pop_conn.list()[1])+ 1)]
#Concat message pieces:
messages = [\\\
.join(mssg [1])for mssg in messages]
#Parse message intom an email object:
messages = [parser.Parser()。parsestr(mssg)for mssg in messages]
消息中的消息:
打印消息['subject']
打印消息['body']
pop_conn.quit()
/ pre>

我的问题是,当我运行这个代码,它正确返回主题,而不是正文。所以如果我发送电子邮件的主题测试员和身体这是一个测试消息它看起来像这样在IDLE。

 >>>>< Tester>>>>>无



<所以似乎正在准确地评估主体而不是身体,我觉得在解析方法上是正确的?问题是,我不清楚这些图书馆是如何改变它,以便它返回主题和正文。

解决方案

对象消息没有正文,您将需要解析多个部分,如下所示:

 部分在message.walk()中:
如果part.get_content_type():
body = part.get_payload(decode = True)

walk()函数通过电子邮件的各个部分进行深度优先迭代,您正在寻找零件具有内容类型。内容类型可以是 text / plain text / html ,有时一个电子邮件可以同时包含如果消息 content_type 设置为 multipart / alternative )。


I would like to receive email using python. So far I have been able to get the subject but not the body. Here is the code I have been using:

import poplib
from email import parser
pop_conn = poplib.POP3_SSL('pop.gmail.com')
pop_conn.user('myusername')
pop_conn.pass_('mypassword')
#Get messages from server:
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
# Concat message pieces:
messages = ["\n".join(mssg[1]) for mssg in messages]
#Parse message intom an email object:
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
for message in messages:
    print message['subject']
    print message['body']
pop_conn.quit()

My issue is that when I run this code it properly returns the Subject but not the body. So if I send an email with the subject "Tester" and the body "This is a test message" it looks like this in IDLE.

>>>>Tester >>>>None

So it appears to be accurately assessing the subject but not the body, I think it is in the parsing method right? The issue is that I don't know enough about these libraries to figure out how to change it so that it returns both a subject and a body.

解决方案

The object message does not have a body, you will need to parse the multiple parts, like this:

for part in message.walk():
    if part.get_content_type():
        body = part.get_payload(decode=True)

The walk() function iterates depth-first through the parts of the email, and you are looking for the parts that have a content-type. The content types can be either text/plain or text/html, and sometimes one e-mail can contain both (if the message content_type is set to multipart/alternative).

这篇关于如何使用python接收邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆