Search code examples
pythonpython-3.xemailgmailimap

Reading Gmail Email in Python


I am attempting to create a simple script to check my Gmail for emails with a certain title. When I run this program on Python 3.7.3 I receive this data: ('OK', [b'17']).

I need to access the body of the email within python. I am just not sure what to do with the data that I have.

Here is my current code:

import imaplib
import credentials

imap_ssl_host = 'imap.gmail.com'
imap_ssl_port = 993
username = credentials.email
password = credentials.passwd
server = imaplib.IMAP4_SSL(imap_ssl_host, imap_ssl_port)

server.login(username, password)
server.select('INBOX')

data = server.uid('search',None, '(SUBJECT "MY QUERY HERE!")')
print(data)

The result from running the code:

('OK', [b'17'])

I know it is a little rough, but I am still learning, so any advice you have to help me improve would be greatly appreciated!


Solution

  • You need to first list the contents of the selected mailbox and fetch one of the items. You could do something like this (also check the link suggested by @asynts)

        imap.select('Inbox')
        status, data = imap.search(None, 'ALL')
        for num in data[0].split():
          status, data = imap.fetch(num, '(RFC822)')
          email_msg = data[0][1]
    

    If you only want specific fields in the body, instead of parsing the RFC you could filter fields like:

        status, data = imap.fetch(num, '(BODY[HEADER.FIELDS (SUBJECT DATE FROM TO)])')