How to write a simple email listener in Python

Question

I'm completely new to Python (v2.7) and I need to write a simple program that runs continuously, listens to a gmail account and calls a function when said account receives an email. So far it seems like using either Python's built-in IMAP or SMTP libraries seems like the best option but I'm not very familiar with them, let alone Python itself.

What I've come up with so far is able to connect to the email and find the most recent email via IMAP4 but it's lacking a way to continuously check whether a new email has been received:

(Source)

import imaplib
import email

#logs in to the desired account and navigates to the inbox
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('email@gmail.com','password')
mail.list()
mail.select('inbox')

result, data = mail.search(None,'ALL')

#retrieves the latest (newest) email by sequential ID
ids = data[0]
id_list = ids.split()
latest_email_id = id_list[-1]

Any help on how I can adjust this to continuously run and check for new incoming messages would be great. Thanks!


Show source
| email   | python   | python-2.7   | imap   | smtp   2017-01-07 03:01 1 Answers

Answers to How to write a simple email listener in Python ( 1 )

  1. 2017-01-07 12:01

    Use the threading module and subclass threading.Thread. Documentation can be found here: https://docs.python.org/2/library/threading.html

    import threading
    import time
    
    class MailThread(threading.Thread):
    

    then your code goes into run() where you have to add some delay. Let's say 1000 seconds.

    def run():
        #your code here
        time.sleep(1000)
    

    The last section of your script looks like this

    if __name__ == '__main__': 
        mail_thread = MailThread()
        mail_thread.start()
        # do other stuff
    

    OR

    Just use a while(True) loop with time.sleep() and a break once you got mail.

Leave a reply to - How to write a simple email listener in Python

◀ Go back