I am trying to read an email from my gmail inbox in Python3. So I followed this tutorial : https://www.thepythoncode.com/article/reading-emails-in-python
My code is the following :
username = "*****@gmail.com"
password = "******"
# create an IMAP4 class with SSL
imap = imaplib.IMAP4_SSL("imap.gmail.com")
# authenticate
imap.login(username, password)
status, messages = imap.select("INBOX")
# total number of emails
messages = int(messages[0])
for i in range(messages, 0, -1):
# fetch the email message by ID
res, msg = imap.fetch(str(i), "(RFC822)")
for response in msg:
if isinstance(response, tuple):
# parse a bytes email into a message object
msg = email.message_from_bytes(response[1])
# decode the email subject
subject = decode_header(msg["Subject"])[0][0]
if isinstance(subject, bytes):
# if it's a bytes, decode to str
subject = subject.decode()
# email sender
from_ = msg.get("From")
# if the email message is multipart
if msg.is_multipart():
# iterate over email parts
for part in msg.walk():
# extract content type of email
content_type = part.get_content_type()
content_disposition = str(part.get("Content-Disposition"))
# get the email body
body = part.get_payload(decode=True).decode()
print(str(body))
imap.close()
imap.logout()
print('DONE READING EMAIL')
The libraries I am using is :
import imaplib
import email
from email.header import decode_header
However, when I execute it I get the following error message, which I don't understand because I never have an empty email in my inbox ...
Traceback (most recent call last):
File "<ipython-input-19-69bcfd2188c6>", line 38, in <module>
body = part.get_payload(decode=True).decode()
AttributeError: 'NoneType' object has no attribute 'decode'
Anyone has an idea what my problem could be ?