This is a short tutorla about
libgmail. Which is a Library to provide access to Gmail via
Python.
Tabs are important in python as they indicate the different code blocks, since they do not have "{" and "}" like those in C and C++. So I'll replace the tabs here with [TAB], since it's hard to write the proper format in HTML.
First of all lets see how can we get the libgmail help, a.k.a man pages:
>>>import libgmail
>>>help(libgmail)
Then lets see how can we retrieve the messages in our the inbox:
>>>import libgmail
>>>ga = libgmail.GmailAccount("username@gmail.com", "password")
>>>ga.login()
>>>folder = ga.getMessagesByFolder("inbox", True)
>>>for thread in folder:
>>>[TAB]print "Thread:", thread.id, "Subject:", thread.subject
>>>[TAB]for msg in thread:
>>>[TAB][TAB]print "Msg:", msg.id, ",Author", msg.author, ",Subject:", msg.subject
Now lets say we want to print all the attached files in all the messages labled by "projectx"
>>>import libgmail
>>>ga = libgmail.GmailAccount("username@gmail.com", "password")
>>>ga.login()
>>>folder = ga.getMessagesByLabel("projectx", True)
>>>for tread in folder:
>>>[TAB]for msg in thread:
>>>[TAB][TAB]for attach in msg.attachments:
>>>[TAB][TAB][TAB]print attach._getContent()
You may also send a message this way:
>>>import libgmail
>>>ga = libgmail.GmailAccount("username@gmail.com", "password")
>>>ga.login()
>>>msg=libgmail.GmailComposedMessage("friend@gmail.com", "SubjectHere", "BodyHere")
>>>ga.sendMessage(msg)
To send attachmented files into the message:
>>>import libgmail
>>>ga = libgmail.GmailAccount("username@gmail.com", "password")
>>>ga.login()
>>>myFiles = ["/file1", "/file2", "/file3"]
>>>msg=libgmail.GmailComposedMessage("friend@gmail.com", "SubjectHere", "BodyHere", filenames=myFiles)
>>>ga.sendMessage(msg)
Finally I've noticed that sometimes the sendMessage() function fails - returns "HTTP Error 404: Not Found", and hope that they are going fix it soon. Actually the function fails on the first time but when you call it again it works, so you may use a "try-except" statement like the one below:
>>>try:
>>>[TAB]ga.sendMessage(msg)
>>>except:
>>>[TAB]ga.sendMessage(msg)
Tags:
Python,
Gmail,
Gr33n Data