I am using Python 3.7.7 and wanted to check my gmail emails with this code:
import smtplib
import time
import imaplib
import email
mail = imaplib.IMAP4_SSL("imap.gmail.com")
mail = imaplib.IMAP4_SSL("imap.gmail.com")
mail.login("[email protected]","mypassword")
mail.select('inbox')
type, data = mail.search(None, 'ALL')
mail_ids = data[0]
id_list = mail_ids.split()
first_email_id = int(id_list[0])
latest_email_id = int(id_list[-1])
for i in range(latest_email_id,first_email_id, -1):
typ, data = mail.fetch(i, '(RFC822)' )
for response_part in data:
if isinstance(response_part, tuple):
msg = email.message_from_string(response_part[1])
email_subject = msg['subject']
email_from = msg['from']
print('From : ') + email_from + '\n'
print('Subject : ')+ email_subject + '\n'
But I am getting this error:
Traceback (most recent call last):
File "C:/Users/jeeva/Desktop/Tanmay_new/python/stackimap.py", line 19, in read_email_from_gmail
typ, data = mail.fetch(i, '(RFC822)' )
File "C:\Program Files\Python37\lib\imaplib.py", line 534, in fetch
typ, dat = self._simple_command(name, message_set, message_parts)
File "C:\Program Files\Python37\lib\imaplib.py", line 1196, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "C:\Program Files\Python37\lib\imaplib.py", line 961, in _command
data = data + b' ' + arg
TypeError: can't concat int to bytes
Please help me. I found the python 2 snippet in this website and converted to python 3.
I noticed that the author likes imap_tools library, a complete response:
High level lib short example:
from imap_tools import MailBox, AND
# get list of email subjects from INBOX folder
with MailBox('imap.mail.com').login('[email protected]', 'password', 'INBOX') as mailbox:
subjects = [msg.subject for msg in mailbox.fetch()]
https://github.com/ikvk/imap_tools