Python - imaplib - View message to specific sender
Asked Answered
D

1

9

I have a python script that is checking emails on Gmail's IMAP server, it displays the latest email on the server. The email address however is receiving emails from multiple different accounts. What would I do to take this script and have it view ONLY messages that are to a specific sender? For example, any email only sent to "[email protected]" will come up.

import imaplib

mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('[email protected]', '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

Thanks in advance! :)

Domingadomingo answered 17/10, 2012 at 23:2 Comment(1)
What happens when you search for the messages you want, instead of "ALL", in mail.search()?Adams
H
6

change:

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

to:

result, data = mail.search(None, '(TO "[email protected]")')
Hess answered 19/10, 2012 at 4:44 Comment(1)
Tx. used it for FROM as well, in case that helps someone else.."""result, data = mail.search(None, '(FROM "[email protected]")')"""Maisey

© 2022 - 2024 — McMap. All rights reserved.