Python Script

Author Gravatar Image MIKEY SKLAR

Now you're ready to write the code to check your GMail IMAP email (using IMAPClient) and light up the red or green LEDs.

Open up a file called checkmail.py with the Nano editor:

Copy Code
nano checkmail.py

...and paste the following code:

Copy Code
#!/usr/bin/env python

from imapclient import IMAPClient
import time

import RPi.GPIO as GPIO

DEBUG = True

HOSTNAME = 'imap.gmail.com'
USERNAME = 'your username here'
PASSWORD = 'your password here'
MAILBOX = 'Inbox'

NEWMAIL_OFFSET = 1   # my unread messages never goes to zero, yours might
MAIL_CHECK_FREQ = 60 # check mail every 60 seconds

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GREEN_LED = 18
RED_LED = 23
GPIO.setup(GREEN_LED, GPIO.OUT)
GPIO.setup(RED_LED, GPIO.OUT)

def loop():
    server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
    server.login(USERNAME, PASSWORD)

    if DEBUG:
        print('Logging in as ' + USERNAME)
        select_info = server.select_folder(MAILBOX)
        print('%d messages in INBOX' % select_info['EXISTS'])

    folder_status = server.folder_status(MAILBOX, 'UNSEEN')
    newmails = int(folder_status['UNSEEN'])

    if DEBUG:
        print "You have", newmails, "new emails!"

    if newmails > NEWMAIL_OFFSET:
        GPIO.output(GREEN_LED, True)
        GPIO.output(RED_LED, False)
    else:
        GPIO.output(GREEN_LED, False)
        GPIO.output(RED_LED, True)

    time.sleep(MAIL_CHECK_FREQ)

if __name__ == '__main__':
    try:
        print 'Press Ctrl-C to quit.'
        while True:
            loop()
    finally:
        GPIO.cleanup()

Don't forget to set the USERNAME and PASSWORD to match your GMail account. (Remember, if you're using two-factor authentication under GMail, you'll need to generate an application-specific password for this. If you're using a different e-mail provider, you may need to check their documentation for what HOSTNAME to use. It's usually something like imap.youremailproviderhere.com.)

Next up, we'll mark the file as executable, so that it can run as a standalone program:

Copy Code
chmod +x checkmail.py

Finally you can run the script! Type in:

Copy Code
sudo ./checkmail.py

Send yourself some emails to see the green LED light up!

You can stop the script at any time by pressing Ctrl-C.

Last updated on 2015-05-04 at 04.25.41 PM Published on 2012-07-29 at 11.58.38 AM