Download a specific email from Gmail using Python

import imaplib
from datetime import datetime, timedelta

obj = imaplib.IMAP4_SSL('imap.gmail.com',993)
obj.login('username','password')
obj.select()

today = datetime.today()
cutoff = today - timedelta(days=5)
dt = cutoff.strftime('%d-%b-%Y')
typ, data = obj.search(None, '(SINCE %s) (FROM "[email protected]")'%(dt,))
print data

I suggest using IMAPClient as it papers over many of the more esoteric aspects of IMAP.

The following snippet will pull messages based on your criteria, parse the message strings to email.message.Message instances and print the Date and From headers.

from datetime import datetime, timedelta
import email
from imapclient import IMAPClient

HOST = 'imap.gmail.com'
USERNAME = 'username'
PASSWORD = 'password'
ssl = True

today = datetime.today()
cutoff = today - timedelta(days=5)

## Connect, login and select the INBOX
server = IMAPClient(HOST, use_uid=True, ssl=ssl)
server.login(USERNAME, PASSWORD)
select_info = server.select_folder('INBOX')

## Search for relevant messages
## see http://tools.ietf.org/html/rfc3501#section-6.4.5
messages = server.search(
    ['FROM "[email protected]"', 'SINCE %s' % cutoff.strftime('%d-%b-%Y')])
response = server.fetch(messages, ['RFC822'])

for msgid, data in response.iteritems():
    msg_string = data['RFC822']
    msg = email.message_from_string(msg_string)
    print 'ID %d: From: %s Date: %s' % (msgid, msg['From'], msg['date'])

import datetime as dt
from imap_tools import MailBox, Q
date = dt.date.today() - dt.timedelta(days=5)
with MailBox('imap.mail.com').login('[email protected]', 'password', 'INBOX') as mailbox:
    for msg in mailbox.fetch(Q(from_='[email protected]', 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

Tags:

Python

Gmail

Imap