Skip to content

Instantly share code, notes, and snippets.

@idlethreat
Created March 31, 2015 02:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save idlethreat/22e171c683e93c89f640 to your computer and use it in GitHub Desktop.
Save idlethreat/22e171c683e93c89f640 to your computer and use it in GitHub Desktop.
Send New Gmail Messages to Graylog
import gmail
from gelfclient import UdpClient
# Script requires libraries from the following fine sources:
#
# Gmail - https://github.com/charlierguo/gmail
# Gelfclient - https://github.com/Graylog2/gelfclient
# IP address of your graylog instance
myGraylogServer = 'your_server_ip_here'
username = "your_username@gmail.com"
password = "your_gmail_password"
def send_gelf_message(g_message_id,g_sent_at,g_from,g_subject,g_body):
gelf_server = myGraylogServer
gelf = UdpClient(gelf_server, port=12201, mtu=8000, source='gmail')
data = {}
data['email_message_id'] = g_message_id
data['email_sent'] = g_sent_at
data['email_from'] = g_from
data['short_message'] = g_subject
data['full_message'] = g_body
gelf.log(data)
# setup our gmail login
g = gmail.login(username, password)
# Build an unread_emails object.
# We're looking only for email messages that are unread.
unread_emails = g.inbox().mail(unread=True)
# set our loop to zero
count = 0
# This iterates over the list of unread emails and puts them into variables.
# Those variables are then submitted to the send_gelf_message function to send off
# finally, all emails are set as read.
for msg in unread_emails:
while count < len(unread_emails):
unread_emails[count].fetch()
message_id = unread_emails[count].message_id
sent_at = str(unread_emails[count].sent_at)
sent_from = unread_emails[count].fr
subject = unread_emails[count].subject
body = unread_emails[count].body
# for debugging
# print sent_at, message_id, sent_from, subject
send_gelf_message(message_id,sent_at,sent_from,subject,body)
# for debugging
# print "marking message as read."
unread_emails[count].read()
# move counter to the next email
count = count + 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment