Download a specific email from Gmail using Python

Viewed 12454

Can someone help me customize an existing code sample?

I can see from the following article how to connect to gmail and download content, but I can't figure out how to search for a specific email and only download the timestamp and body?

ARTICLE: How can I download all emails with attachments from Gmail?

I specifically want to grab the emails from "Alerts@foobank.com" for the last 5 days and download the send time and body of the emails. I'll then parse this to determine which emails I need to use.

I'm self-taught and am having a hard time customizing the script above to do this.

Any help is much appreciated. Thanks.

JD

3 Answers
import datetime as dt
from imap_tools import MailBox, Q
date = dt.date.today() - dt.timedelta(days=5)
with MailBox('imap.mail.com').login('test@mail.com', 'password', 'INBOX') as mailbox:
    for msg in mailbox.fetch(Q(from_='Alerts@foobank.com', date_gte=date)):
        sent_time = msg.date
        body = msg.text or msg.html
        for att in msg.attachments:
            att.filename         # str: 'cat.jpg'
            att.content_type     # str: 'image/jpeg'
            att.payload          # bytes: b'\xff\xd8\xff\xe0\'

*Note that there is no imap search criteria "with attachments"

https://github.com/ikvk/imap_tools

Related