Skip to content

Instantly share code, notes, and snippets.

@wess
Created December 8, 2011 20:45
Show Gist options
  • Save wess/1448496 to your computer and use it in GitHub Desktop.
Save wess/1448496 to your computer and use it in GitHub Desktop.
Use python to read Gmail and post to a web service
#
# gmail_to_post.py
# FrenzyLabs, llc (@frenzylabs)
#
# Created by Wess Cope (@wesscope) on 2011-12-08.
# Copyright 2011 FrenzyLabs, llc. All rights reserved.
#
# Using:
# Python 2.7
# Requests: http://python-requests.org
#
# A quick and dirty python script to check for unread messages
# in Gmail account and post them to a web service/url.
#
import sys, imaplib, email
from StringIO import StringIO
MAIL_SERVER = "imap.gmail.com"
MAIL_PORT = 993
class FromGmailToPost(object):
def __init__(self, username, password):
self.username = username
self.password = password
self.connection = imaplib.IMAP4_SSL(MAIL_SERVER, MAIL_PORT)
self.connection.login(username, password)
self.connection.select()
def parse_attachment(self, message_part):
content_disposition = message_part.get("Content-Disposition", None)
if content_disposition:
dispositions = content_disposition.strip().split(";")
if bool(content_disposition and dispositions[0].lower() == "attachment"):
file_data = message_part.get_payload(decode=True)
attachment = StringIO()
attachment.write(file_data)
attachment.content_type = message_part.get_content_type()
attachment.size = len(file_data)
attachment.name = None
attachment.create_date = None
attachment.mod_date = None
attachment.read_date = None
for param in dispositions[1:]:
name,value = param.split("=")
name = name.lower()
attachment.name = value.replace('"', '')
return attachment
return None
def fetch_unseen(self):
msg_type, data = self.connection.search(None, "UNSEEN")
for item in data[0].split():
msg_type, msg_data = self.connection.fetch(item, '(RFC822)')
for part in msg_data:
if isinstance(part, tuple):
sent_to = ""
sent_from = ""
subject = ""
body = ""
attachments = []
email_msg = email.message_from_string(part[1])
sent_to = email_msg.get('to')
sent_from = email_msg.get('from')
subject = email_msg.get('subject')
for step in email_msg.walk():
if step.get_content_type() == 'text/plain':
body = step.get_payload()
attachment = self.parse_attachment(step)
if attachment:
attachments.append(attachment)
self.post_message(message={
"to": sent_to,
"from": sent_from,
"subject": subject,
"body-plain": body,
"attachments": attachments
})
def post_message(self, message):
import requests
from tempfile import NamedTemporaryFile
files = {}
for f in message.pop("attachments"):
name, ext = f.name.split('.')
# tmp = NamedTemporaryFile(mode="w+b", prefix=name, suffix=ext)
# tmp.write(f.getvalue())
f.seek(0)
files[f.name] = f
response = requests.post("http://url/to/post/too", data=message, files=files)
print
print response.content
print
if __name__ == "__main__":
g = FromGmailToPost('username@gmail_domain.com', 'password')
g.fetch_unseen()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment