This script will:
- Log into Gmail Pop
- Read the email
- Delete the read email
- Insert the email’s text into a MySql database
- Sleep for 1800 seconds, and repeat
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | try: import poplib, sys, time import string, random import StringIO, rfc822 import datetime SERVER = "pop.gmail.com" USER = "gmailusername" PASSWORD = "gmailpassword" i = 0; print """ |------------------------------------------| | This is a python program that checks a | | POP account and if there is a message, | | it adds it to the SQL server. | |------------------------------------------| by: Daniel Folkes email: [email protected] (every 180 seconds) Checking POP server.... """ while 1: try: server = poplib.POP3_SSL(SERVER, 995) server.user(USER) server.pass_(PASSWORD) except: print "error setting up server." resp, items, octets = server.list() # download a random message try: id, size = string.split(items[0]) resp, text, octets = server.retr(id) text = string.join(text, "\n") file = StringIO.StringIO(text) note = "" name = "" message = rfc822.Message(file) for k, v in message.items(): if k=='from': name = v[:12] note = message.fp.read()[:50] print "note: ", note server.dele(1) #this will delete the message after you read it server.quit() #------------------------------------------- if note !="": import MySQLdb db = MySQLdb.connect(host="localhost", user="USERNAME", passwd="PASSWORD",db="DATABASENAME") cur2 = db.cursor() if name: cur2.execute("INSERT INTO note (note, name) VALUES (%s, %s)", (note, name)) else: cur2.execute("INSERT INTO note (note) VALUES (%s)", (note)) except: i+=1 #print "Unexpected error:", sys.exc_info()[0] time.sleep(1800) except: print "Failed Unexpectedly" |
Your code really helped me get a good concept using both Python and MySQLdb module. I want to grab my email and insert into a hosting service server on which MySQL is installed, however not in my local database. I changed localhost to the my web address, but it doesn’t work. I have no idea how to solve this. Could you help me?
Hmmm. Some hosting providers don’t allow external access to their SQL servers. So, you need to confirm with them about that.
Otherwise, it should work fine.