Python gmail从特定的消息中读取新消息

时间:2015-07-04 18:38:10

标签: python gmail imaplib

我需要阅读我的Gmail邮件,但我不知道如何阅读邮件正文的内容,希望你能帮助我,非常感谢你!

如果我使用while循环进行协作也很有帮助。

import imaplib

print "Bienvenido"

print "Logueando email.."

email = "email@gmail.com"
passwd = "password"

conn = imaplib.IMAP4_SSL('imap.gmail.com')

try:
        conn.login(email, passwd)
except:
        print sys.exc_info()[1]
        sys.exit(1)

print "Ok"

print "Seleccionando emails del banco.."

conn.select('INBOX')

def emails_from(name):
    status, response = conn.search(None, '(FROM "%s")' % name)
    email_ids = [e_id for e_id in response[0].split()]
    print "Ok"
    print "Revisando si llego el correo.."
    ids = email_ids[-1]
    print ids
    if ids == '279':
        print "no tiene nuevo correo" #---------BUCLE WHILE TRUE HERE.
    else:
        print "si tiene nuevo correo" #---------READ BODY FROM ID.

    print "Ok"
    return email_ids

emails_from(email)

print "Bye"

1 个答案:

答案 0 :(得分:0)

您想使用conn.fetch方法。这是imaplib的例子:

import getpass, imaplib

M = imaplib.IMAP4()
M.login(getpass.getuser(), getpass.getpass())
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')
    print 'Message %s\n%s\n' % (num, data[0][1])
M.close()
M.logout()

所以可能只是这样做:

typ, data = conn.fetch(ids, '(RFC822)')