7

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!

asynts
  • 2,213
  • 2
  • 21
  • 35
Python Project
  • 73
  • 1
  • 1
  • 5

1 Answers1

4

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)])')
Josep Valls
  • 5,483
  • 2
  • 33
  • 67
  • That worked! Now I can run "print(email_msg)" at the end of my program, and it gives me the information in the header of my email. I have two questions though. Is there any way that I can access the body of the email? Is there a list of commands that I can reference for the "imap.fetch" function? When I say a list of commands I mean how did you know what to put in the parentheses of the "imap.fetch()" function? Sorry for my ignorance. I am still learning. Thank you for your help! – Python Project Apr 11 '19 at 16:54
  • imaplib is a low level library. You'll need to understand a lot more (eg, RFC 3501) to know what to put. Alternatively you can try something higher level. I've heard people use imapclient here; or use gmail's HTTP apis, which are probably easier to understand – Max Apr 11 '19 at 17:18
  • Thank you for the advice, Max. If I want to find the body specifically instead of the header would you suggest I look in the gmail HTTP apis? – Python Project Apr 11 '19 at 17:34
  • user.message has a body field in HTTP. I've not used it myself. But the guides and documentations have built in HTTP "Try It" buttons for experimenting. You could start here, https://developers.google.com/gmail/api/v1/reference/users/messages/get or go back and read some overview guides. – Max Apr 11 '19 at 17:59