# Check mail and trigger the blink(1) when new mail is found import os, sys, imaplib, email, getopt, time from subprocess import Popen, DEVNULL class MailBlinker(): def __init__(self, quiet=False): # GMail username/password self.username = 'your_gmail_username' self.password = 'your_gmail_password' # Location of the blink1control-tool # (make sure API is enabled in blink1Control GUI) self.blinker_tool = 'C:/Program Files/Blink1Control/blink1control-tool.exe' # How many seconds between checks? self.mail_check_interval = 30 # Should access be read-only? (If False, then blink(1) will only be triggered once, the first time # a new message is seen. If True, blink(1) will see the new message every time it checks until the # mail is marked as "seen" in another mail reader.) self.inbox_read_only = True # The mail connection handler self.mailconn = None # Should we print any output? self.quiet = quiet ######################################################################## # Connect to GMail def connect(self): self.mailconn = imaplib.IMAP4_SSL('imap.gmail.com') (retcode, capabilities) = self.mailconn.login(self.username, self.password) self.mailconn.select('inbox', readonly=self.inbox_read_only) # Check for mail def check_mail(self): # Connect to GMail (fresh connection needed every time) self.connect() num_new_messages=0 (retcode, messages) = self.mailconn.search(None, '(UNSEEN)') if retcode == 'OK': for num in messages[0].split() : num_new_messages += 1 if not self.quiet: print(' Processing #{}'.format(num_new_messages)) typ, data = self.mailconn.fetch(num,'(RFC822)') for response_part in data: if isinstance(response_part, tuple): original = email.message_from_bytes(response_part[1]) if not self.quiet: print(" ", original['From']) print(" ", original['Subject']) typ, data = self.mailconn.store(num,'+FLAGS','\\Seen') return num_new_messages # Blink! def blink(self): cmd = "{} --rgb=#FFFFFF --blink 10 -m 150 -t 300".format(self.blinker_tool) # -t should be about 2x the speed of -m if self.quiet: stdout = DEVNULL stderr = DEVNULL else: stdout = None # to screen stderr = None # to screen Popen(cmd, stdout=stdout, stderr=stderr) ######################################################################## if __name__ == '__main__': # Specify -q for quiet operation (no output) opts, args = getopt.getopt(sys.argv[1:], 'q') quiet = False for opt, arg in opts: if opt == '-q': quiet = True mb = MailBlinker(quiet) while True: if not quiet: print("Checking... ", end='') num_new_messages = mb.check_mail() if not quiet: print("{} new messages".format(num_new_messages)) if num_new_messages > 0: mb.blink() time.sleep(mb.mail_check_interval)