GMAIL, subject checking using python. I thought it would make an interesting post, and I will tell you why. When I was playing with the gmail notifier (about which I posted on earlier), I thought, if I can basically check if a new message has , and if it has, switch on a LED, I can pretty much make everything switch on (or off) over the internet when sending an email. I could for instance switch on an alarm system by sending an email to a gmail account with the code "344alarm2014-on" the python code would pull the email, check the subject an by some logical check switch on the device through GPIO. I can think of dozens of other applications, but let's stick with this one. Let's also stick with switching a LED on or off, to test the code. After that, whatever you want the code to invoke can be bolted on.
#source:http://bitsofpy.blogspot.com.au/2010/05/python-and-gmail-with-imap.html
import imaplib
username="someone@gmail.com"
password="somedude"
imap_server = imaplib.IMAP4_SSL("imap.gmail.com",993)
imap_server.login(username, password)
imap_server.select('INBOX')
# Count the unread emails
status, response = imap_server.status('INBOX', "(UNSEEN)")
unreadcount = int(response[0].split()[2].strip(').,]'))
print unreadcount
#Now I'm not saying this is a particularly nice way of doing #this, but if you print the response and reverse engineer
#it you will see how I arrived with that string parsing.
#Regex would be another option, but I try avoid that unless it is #required.
#Now lets get a list of the identifiers for each unread message, #I'm going to call it email_ids:
# Search for all new mail
status, email_ids = imap_server.search(None, '(UNSEEN)')
print (email_ids)
def get_emails(email_ids):
data = []
for e_id in email_ids:
_, response = imap_server.fetch(e_id, '(UID BODY[TEXT])')
data.append(response[0][1])
return data
def get_subjects(email_ids):
subjects = []
for e_id in email_ids:
_, response = imap_server.fetch(e_id, '(body[header.fields (subject)])')
subjects.append( response[0][1][9:] )
return subjects
#And I often search for emails from someone in particular, I can #do that easily from Python as well:
def emails_from(name):
'''Search for all mail from name'''
status, response = imap_server.search(None, '(FROM"%s")'%name)
email_ids = [e_id for e_id in response[0].split()]
print ('Number of emails from %s: %i. IDs: %s' % (name, len(email_ids), email_ids))
return email_ids
something worth checking:#!/usr/bin/env python
import subprocess, feedparser
DEBUG = 1
USERNAME = "myusername" # just the part before the @ sign, add yours here
PASSWORD = "mypassword"
NEWMAIL_OFFSET = 0 # my unread messages goes to zero, yours might not
MAIL_CHECK_FREQ = 60 # check mail every 60 seconds
while True:
newmails = int(feedparser.parse("https://" + USERNAME + ":" + PASSWORD +"@mail.google.com/gmail/feed/atom/sunset")["feed"]["fullcount"])
if newmails > NEWMAIL_OFFSET:
subprocess.call(["python relay-test.py",],shell=True)
else:
pass
time.sleep(MAIL_CHECK_FREQ)
background info:
http://bruno.im/2010/jul/29/europython-talk-python-and-imap-protocol/
https://pythonadventures.wordpress.com/tag/gmail/
gmail python library:
https://github.com/charlierguo/gmail