SMS through email, and checking your gmail account in python

Submitted by pokharel@fas.ha... on Tue, 03/17/2009 - 18:49.

Our team dealt with text messages by using the email gateways that providers provide in the US to text messages. (Look here for info: http://en.wikipedia.org/wiki/SMS_gateway)

The idea is this: you can send email from a text, and the email comes in as being from an email address that is tied to a phone. If you just reply to this address, then you will get a text message on the phone the first message was sent from. From my t-mobile phone, I text the number 500 with the message "cfa.baddate@gmail.com/no subject/some text" and the gmail account receives an email from 9703146388@tmomobile.com. When I reply to 9703146388@tmomobile.com, I get a text sent to my phone.

So really, you can treat txts as short emails, and just use a library like libgmail (libgmail.sourceforge.net) to deal with gmail. Posted is selected parts of my code that you should be able to use once you have libgmail to send emails, also known as texts if you have the right numbers.


class some_class:
def __init__(self,using_gmail = False):
self.db = load_db()
self.using_gmail = using_gmail
if self.using_gmail:
self.ga = libgmail.GmailAccount('cfa.baddate@gmail.com','CsikNadav')
self.ga.login()

def recheck_gmail(self):
if not self.using_gmail:
print "Not using gmail. Stop being absurd."
else:
print "Checking gmail for messages..\n"
folder = self.ga.getUnreadMessages()
for thread in folder:
for msg in thread:
content = self.process_email(msg.source)
send_number = msg.sender
self.process(content,send_number,datetime.datetime.now())

def text(self,number,msg):
if self.using_gmail:
gmsg = libgmail.GmailComposedMessage(number, "CFA Bad Date Report", msg)
if self.ga.sendMessage(gmsg):
print "Message sent to ",number,"\n--\n",msg,"\n--\n"
else:
print "Unable to send message to",number,"\n--\n",msg,"\n--\n"
else:
print "pretend to send message to",number,"\n--\n",msg,"\n--\n"

And here's a simple outer loop using the code (for python 2.5 "from __future__ import with_statement", should work without any mods for python 2.6)

sa = some_class(using_gmail = True)
while(True):
sa.recheck_gmail()
sa.save()
time.sleep(60)

Note: this code probably won't just work. This are just snippets of my code. Attached is the complete code. Needs a db.txt with a python dictionary.