How to read mail from Gmail using Python Code?

Python code to connect to Gmail via IMAP and read mails in the inbox     



Settings Needed


Connect to Gmail and open settings.






Open IMAP and POP settings



Enable IMAP access



We can run our Python Code now.


# Program to read Gmail using IMAP. Internet Mail Access Protocol


"""
We use the Imbox library to read email from Gmail

"""

from imbox import Imbox

# documentation of Imbox https://pypi.org/project/imbox/

try: # Call the constructor of Imbox
myinbox = Imbox('imap.gmail.com', username='mymail@gmail.com', password='mypassword',
ssl=True,
ssl_context=None,
starttls=False)
except Exception as e:
print("Error in connecting to Gmail: ", e)
exit(1) # End the program if you cannot connect
inboxmessages = myinbox.messages() # Get all inbox messages
count = 1
for uid, message in inboxmessages: # Loop through the inbox messages and print
print(count, ") Mail\nSubject:", message.subject)
count += 1
messagebody = message.body.get("plain")[0]
print(messagebody)

# End Program

Output






1 ) Mail
Subject: Hello Varanasi Software Junction
Hello Varanasi Software Junction, should I come and join today.

2 ) Mail
Subject: 🙏 sir ji
Hello


Process finished with exit code 0










Post a Comment

0 Comments

Me