Skip to content

Instantly share code, notes, and snippets.

@shapr
Created May 21, 2013 23:13
Show Gist options
  • Save shapr/5624036 to your computer and use it in GitHub Desktop.
Save shapr/5624036 to your computer and use it in GitHub Desktop.
Part of the code I use to check gvoice SMS messages on my laptop and Raspberry Pi
import sqlite3 as lite
import imaplib
import email
# assume gtk is all good
import gnotify
# assume db has been setup correctly
def createtyrnidb():
"""msg.keys ['Delivered-To', 'Received', 'Return-Path', 'Received-SPF', 'Authentication-Results', 'Received', 'DKIM-Signature', 'MIME-Version', 'Received', 'References', 'Message-ID', 'Date', 'Subject', 'From', 'To', 'Content-Type']
"First Last (SMS)" <[email protected]>
SMS from First Last [(256) 555-1212]"""
con = lite.connect('tyrni.db')
with con:
cur = con.cursor()
cur.execute("CREATE TABLE SMS(Id INTEGER PRIMARY KEY, messageid varchar(255), Subject varchar(255),Body text") # sure, why not?
def getsms():
totalsms = 0
errorsms = 0
con = lite.connect('tyrni.db')
cur = con.cursor()
# pull out all message-id values from the local db
midrows = cur.execute('select messageid from sms;').fetchall()
mids = map(lambda x:x[0],midrows)
print 'mids are',mids
M = imaplib.IMAP4_SSL('imap.gmail.com')
M.login('[email protected]', 'password')
M.select()
typ, data = M.search(None, 'SUBJECT', 'SMS') # Google Voice SMS email will have Subject starting with 'SMS'
for num in data[0].split():
totalsms += 1
typ, data = M.fetch(num,'(RFC822)')
msg = email.message_from_string(data[0][1])
# ignore message-id values we've already seen
this_mid = msg['Message-ID']
print 'checking',this_mid
if not (msg['Message-ID'] in mids):
print 'inserting',this_mid,msg['Subject']
try:
cur.execute("INSERT INTO SMS(messageid, subject, body) VALUES(?, ?, ?);", (msg['Message-ID'],msg['Subject'],msg.get_payload())) # XXX is get_payload correct?
gnotify.gnotify(msg['Subject'],msg.get_payload())
except lite.InterfaceError, e:
errorsms += 1
print e,"good luck with that"
else: print "we've already got",this_mid
con.commit()
print 'ok, latest messages loaded into the database'
print totalsms,' total messages found and ',errorsms,'messages had errors when inserting to the db.'
# Is this the right order?
M.close()
M.logout()
def vartest():
con = lite.connect('tyrni.db')
cur = con.cursor()
midrows = cur.execute('select messageid from sms;').fetchall()
mids = map(lambda x:x[0],midrows)
print 'mids are',mids
print "is 'test' in mids?"
if 'test' in mids:
print 'we found it!'
else:
print "You wish!"
if __name__ == '__main__':
getsms()
#vartest()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment