Python-imaplib-查看发送给特定发件人的消息

2022-04-09 00:00:00 python imap gmail

问题描述

我有一个在Gmail的IMAP服务器上检查电子邮件的Python脚本,它显示服务器上的最新电子邮件。然而,该电子邮件地址正在接收来自多个不同账户的电子邮件。要使用此脚本并使其仅查看发送给特定发件人的邮件,我应该做些什么?例如,只发送到"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

提前谢谢!:)


解决方案

更改:

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

收件人:

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

相关文章