通过python检查Gmail帐户的新邮件

时间:2016-10-28 08:48:48

标签: python email gmail python-2.x poplib

我使用此代码检查延迟10秒的新邮件。

import poplib
from email import parser
import time

def seeit(): 
    pop_conn = poplib.POP3_SSL('pop.gmail.com')
    pop_conn.user('xxx')
    pop_conn.pass_('xx')
    #Get messages from server:
    messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
    # Concat message pieces:a
    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']
    pop_conn.quit()


starttime=time.time()

while True:
    k=10.0
    print "tick"
    seeit()
    time.sleep(k - ((time.time() - starttime) % k))

如何检索没有标题的电子邮件正文?

1 个答案:

答案 0 :(得分:0)

查看get_payload()包中的方法email方法。

从服务器获取消息后尝试此操作:

import email

...
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
...

for i in messages:
    mssg = email.message_from_string(i)
    print(mssg.get_payload())