Home > Software design >  How do you get unread emails from Gmail with smtplib with Python3
How do you get unread emails from Gmail with smtplib with Python3

Time:09-23

I recently found this script online to send emails with the smtplib library for python.

import smtplib as smtp

connection = smtp.SMTP_SSL('smtp.gmail.com', 465)

email_addr = '[email protected]'
email_passwd = 'password'
connection.login(email_addr, email_passwd)
connection.sendmail(from_addr=email_addr, to_addrs='[email protected]', msg="Sent 
from my IDE. Hehe")
connection.close()

How do I receive new emails?

Maybe by running something similar to connection.sendmail, like this: 'connection.getmail'

Thanks in advance!

CodePudding user response:

I wouldn't bother with the smtp server for this.

The easiest way to do what you want is to use the Gmail api. There is a QuickStart for python available.

If you want to know when you get a new email then you should set up a watch to catch push notifications.

request = {
  'labelIds': ['INBOX'],
  'topicName': 'projects/myproject/topics/mytopic'
}
gmail.users().watch(userId='me', body=request).execute()

Your application will then be notified when ever a new mail arrives. Beyond that user message list will give you a list of all the messages for a given user.

  • Related