Python - imaplib - 查看特定发件人的邮件

时间:2012-10-17 23:02:57

标签: python gmail imap

我有一个python脚本正在检查Gmail的IMAP服务器上的电子邮件,它会在服务器上显示最新的电子邮件。但是,电子邮件地址正在接收来自多个不同帐户的电子邮件我该怎么做才能获取此脚本并让它仅查看特定发件人的邮件?例如,任何发送到“johndoe@gmail.com”的电子邮件都会出现。

import imaplib

mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('myemail@gmail.com', 'password123')
mail.list()
# Out: list of "folders" aka labels in gmail.
mail.select("inbox") # connect to inbox.

result, data = mail.search(None, "ALL")

ids = data[0] # data is a list.
id_list = ids.split() # ids is a space separated string
latest_email_id = id_list[-1] # get the latest

result, data = mail.fetch(latest_email_id, "(RFC822)") # fetch the email body (RFC822) for the given ID

raw_email = data[0][1] # here's the body, which is raw text of the whole email
# including headers and alternate payloads

提前致谢! :)

1 个答案:

答案 0 :(得分:4)

变化:

result, data = mail.search(None, "ALL")

为:

result, data = mail.search(None, '(TO "johndoe@gmail.com")')