如何使用python接收邮件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4908472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 18:03:25  来源:igfitidea点击:

How to receive mail using python

pythonemail

提问by Matthew Downey

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:

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

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”且正文为“This is a test message”的电子邮件,它在 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.

所以它似乎准确地评估了主题而不是身体,我认为它在解析方法中对吗?问题是我对这些库知之甚少,无法弄清楚如何更改它以便它同时返回主题和正文。

回答by senderle

The email parser returns an email.message.Messageobject, which does not contain a bodykey, as you'll see if you run

电子邮件解析器返回一个email.message.Message对象,该对象不包含body密钥,您将在运行时看到

print message.keys()

What you want is the get_payload()method:

你想要的是get_payload()方法:

for message in messages:
    print message['subject']
    print message.get_payload()
pop_conn.quit()

But this gets complicated when it comes to multi-part messages; get_payload()returns a list of parts, each of which is a Messageobject. You can get a particular part of the multipart message by using get_payload(i), which returns the ith part, raises an IndexErrorif iis out of range, or raises a TypeErrorif the message is not multipart.

但是当涉及到多部分消息时,这会变得复杂;get_payload()返回一个部件列表,每个部件都是一个Message对象。您可以使用 获取多部分消息的特定部分get_payload(i),它返回第ith 部分,引发IndexErrorifi超出范围,或引发 aTypeError如果消息不是多部分。

As Gustavo Costa De Oliveir points out, you can use the walk()method to get the parts in order -- it does a depth-first traversal of the parts and subparts of the message.

正如 Gustavo Costa De Oliveir 指出的那样,您可以使用该walk()方法按顺序获取部分——它对消息的部分和子部分进行深度优先遍历。

There's more about the email.parsermodule at http://docs.python.org/library/email.message.html#email.message.Message.

有关该email.parser模块的更多信息,请访问http://docs.python.org/library/email.message.html#email.message.Message

回答by Gustavo Costa De Oliveira

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/plainor text/html, and sometimes one e-mail can contain both (if the message content_typeis set to multipart/alternative).

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

回答by rootart

it also good return data in correct encoding in message contains some multilingual content

它也很好地返回消息中正确编码的数据包含一些多语言内容


charset = part.get_content_charset()
content = part.get_payload(decode=True)
content = content.decode(charset).encode('utf-8')

回答by Rolly Maulana Awangga

if u want to use IMAP4. Use outlook python library, download here : https://github.com/awangga/outlookto retrieve unread email from your inbox :

如果你想使用 IMAP4。使用 Outlook python 库,在此处下载:https: //github.com/awangga/outlook从收件箱中检索未读电子邮件:

import outlook
mail = outlook.Outlook()
mail.login('[email protected]','yourpassword')
mail.inbox()
print mail.unread()

to retrive email element :

检索电子邮件元素:

print mail.mailbody()
print mail.mailsubject()
print mail.mailfrom()
print mail.mailto()