Now you're ready to download some Python code and check your Gmail account. The following python script can be downloaded directly onto your raspberry pi, customized with your email settings and executed to illuminate the LEDs.

# SPDX-FileCopyrightText: 2019 Mikey Sklar for Adafruit Industries
#
# SPDX-License-Identifier: MIT

import time
import board
from imapclient import IMAPClient
from digitalio import DigitalInOut, Direction

HOSTNAME = 'imap.gmail.com'
MAILBOX = 'Inbox'
MAIL_CHECK_FREQ = 60        # check mail every 60 seconds

# The following three variables must be customized for this
# script to work
USERNAME = 'your username here'
PASSWORD = 'your password here'
NEWMAIL_OFFSET = 1          # my unread messages never goes to zero, use this to override

# setup Pi pins as output for LEDs
green_led = DigitalInOut(board.D18)
red_led = DigitalInOut(board.D23)
green_led.direction = Direction.OUTPUT
red_led.direction = Direction.OUTPUT

def mail_check():
    # login to mailserver
    server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
    server.login(USERNAME, PASSWORD)

    # select our MAILBOX and looked for unread messages
    unseen = server.folder_status(MAILBOX, ['UNSEEN'])

    # number of unread messages
    # print to console to determine NEWMAIL_OFFSET
    newmail_count = (unseen[b'UNSEEN'])
    print('%d unseen messages' % newmail_count)

    if newmail_count > NEWMAIL_OFFSET:
        green_led.value = True
        red_led.value = False
    else:
        green_led.value = False
        red_led.value = True

    time.sleep(MAIL_CHECK_FREQ)

while True:
    mail_check()

Download the Code

Let's put this file right in your home directory for simplicity. The wget command makes this easy.

$ cd
$ wget https://raw.githubusercontent.com/adafruit/Adafruit_Learning_System_Guides/master/Raspberry_Pi_E-mail_Notifier_Using_LEDs/Raspberry_Pi_E-mail_Notifier_Using_LEDs.py

Customize Mail Variables

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.)

Finally, my INBOX never goes to zero unread messages. We have a variable called NEWMAIL_OFFSET which you can customize to whatever your current unread message count is. When running this python script there will be a number output to the console showing the current number of unseen messages.

Running the Code

$ python3 ./Raspberry_Pi_E-mail_Notifier_Using_LEDs.py

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

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

This guide was first published on Jul 29, 2012. It was last updated on Apr 16, 2024.

This page (Python Script) was last updated on Apr 16, 2024.

Text editor powered by tinymce.