Reading Gmail Email in Python

谁说我不能喝 提交于 2021-02-07 08:33:19

问题


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!


回答1:


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)])')


来源:https://stackoverflow.com/questions/55635990/reading-gmail-email-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!