#!/usr/bin/env python # # COMMAND LINE GMAIL USER INTERFACE # By Joey C. [ http://joeyjwc.x3fusion.com/ ] # # A simple, flexible inteface for working with Gmail. # It uses the libgmail API. import os, sys import libgmail as g ## VARIABLES # Default Account defuser=''; defpass=''; # Menu choices = [ "Send a Message", "Check Number of Unread Emails", "Read Unread Emails", "Read an Email" ] actions = [ "sendMessage()", "getUnread()", "readUnread()", "readEmail()" ] # File Information editor = "/usr/bin/nano -t" tmppath = "/tmp" ## INITIAL FUNCTIONS ## These functions are for setting up the system. def initiateUI(): user = getUsername() password = getPassword() do_login(user, password) showMenu() def getUsername(): if len(sys.argv) > 1: return sys.argv[1] elif defuser == '': return raw_input("Username: ") else: return defuser def getPassword( force=False ): if force==True or defpass == "": from getpass import getpass return getpass("Password: ") else: return defpass def do_login(user, password): global acct acct = g.GmailAccount(user, password) print "> LOGGING IN [ %s ]" % user try: acct.login() except g.GmailLoginFailure: print "! FAILED" password = getPassword(True) do_login(user, password) def showMenu(): print "\n> MAIN MENU" n = 1 for item in choices: print "%s. %s" %(n,item) n += 1 print "%s. Exit" % n choice = raw_input("#: ") try: choice = int(choice) except ValueError: showMenu() else: if choice > n: showMenu() elif choice == 5: quitUI() else: print "\n\n" exec actions[choice-1] askNext() def askNext(): print "" print "[ENTER] Main Menu" print "[Q] Quit" ans = raw_input(": ") if ans.lower() == "q": quitUI() else: showMenu() def quitUI(): print "Goodbye!" sys.exit ## COMMON FUNCTIONS ## These functions are used across multiple menu items. ## UI RELATED def getBodyText(): from time import time global msg_filename curtime = int(time()) msg_filename = "gmailui_msg_%s" % curtime os.chdir(tmppath) command = "%s %s" %(editor, msg_filename) os.system(command) f = open(msg_filename, "r") return f.read() ## LIBGMAIL RELATED def do_sendmsg( to, subj, body ): print "\n> SENDING %s TO %s" %(subj, to) gmailmsg = g.GmailComposedMessage(to, subj, body) if acct.sendMessage(gmailmsg): print "> SENT." os.remove("%s/%s" %(tmppath, msg_filename)) else: print "! FAILED." print " You can retrieve your message by going to:" print " %s/%s" %(tmppath, msg_filename) ## MENU FUNCTIONS ## These functions relate to specific menu items. ## SEND AN EMAIL def sendMessage(): print "> SEND A MESSAGE" message = getSendInfo() do_sendmsg(message[0], message[1], message[2]) def getSendInfo(): # TODO: Add error checking. to = raw_input("To: ") subj = raw_input("Subject: ") body = getBodyText() print "Body:" print body return [ to , subj , body ] ## GET NUMBER OF UNREAD MESSAGES def getUnread(): unread = acct.getUnreadMsgCount() print "> NUMBER OF UNREAD EMAILS" print "You have %s new emails" % unread # Initiate. initiateUI()