I am using the below code to read an unread email.
In mail.fetch
method, getting typ,data as a returned parameters and we are accessing the raw email with raw_email = data[0][1]
. Could anyone explain why we are hardcoding the index as [0][1]
for getting the message? Is that any proper way to get message without doing any hardcode?
Python code below:
import imaplib
mail = imaplib.IMAP4_SSL('imap.gmail.com')
try:
mail.login(email_user, email_pass)
status, messages = mail.select("INBOX")
(retcode, emailnums) = mail.search(None,'(UNSEEN)')
if retcode == 'OK':
for emailnum in emailnums[0].split():
typ,data = mail.fetch(emailnum,'(RFC822)')
raw_email = data[0][1]
#converts byte literal to string removing b''
raw_email_string = raw_email.decode('utf-8')
email_message = email.message_from_string(raw_email_string)