Skip to content

Instantly share code, notes, and snippets.

@develmaycare
Created October 20, 2010 12:49
Show Gist options
  • Save develmaycare/636350 to your computer and use it in GitHub Desktop.
Save develmaycare/636350 to your computer and use it in GitHub Desktop.
Tinkering I've done to check email and import the result in to a Django application.
#! /usr/bin/env python
"""
Import email for a given frequency. For example, to activate importers set
up for every 15 minutes, run:
./import_email.py 15
Set this up in your crontab for 5, 10, 15, 30, 45, and 60 as needed.
*/5 * * * * import_email.py 5 > /dev/null 2>&1
*/10 * * * * import_email.py 10 > /dev/null 2>&1
*/15 * * * * import_email.py 15 > /dev/null 2>&1
*/30 * * * * import_email.py 30 > /dev/null 2>&1
*/45 * * * * import_email.py 45 > /dev/null 2>&1
*/60 * * * * import_email.py 60 > /dev/null 2>&1
"""
# Imports #
import getopt
import os
import re
import sys
# Settings #
sys.path = ['../../'] + sys.path
os.environ['DJANGO_SETTINGS_MODULE'] = "nsite.settings"
# Imports #
from django.contrib.auth.models import User
from tickets.models import *
# Procedure #
# Need to do this in order to get the frequency pass on the command line.
try:
opts,args = getopt.getopt(sys.argv[1:],'h')
except getopt.GetoptError, error:
print str(error)
sys.exit(2)
# Make sure the frequency arguments has actually been given.
try:
minutes = args[0]
except IndexError, error:
print "Frequency argument is required. Example: "
print "./import_email.py 15"
sys.exit(2)
# "Print" documentation is used from here.
print "Importing python's poplib and email modules."
import poplib
from email import parser
print "Fetching those settings configured for %s minute import." %minutes
importers = Mail_Import.objects.filter(frequency__exact=minutes)
for Config in importers:
print "Initializing the connection for %s" %Config.site
Conn = poplib.POP3(Config.host)
Conn.user(Config.user)
Conn.pass_(Config.password)
print "Downloading messages."
messages = [Conn.retr(i) for i in range(1, len(Conn.list()[1]) + 1)]
messages = ["\n".join(m[1]) for m in messages]
messages = [parser.Parser().parsestr(m) for m in messages]
message_id = 1
for message in messages:
print "Extracting the From header to find the email address."
try:
email = re.findall('[a-zA-Z0-9+_\-\.]+@[0-9a-zA-Z][.-0-9a-zA-Z]*.[a-zA-Z]+',message['from'])[0]
except Exception, error:
print "Couldn't find an email address within the From header. I can't go on."
continue
print "Make sure the message is from an approved user."
U = User.objects.get(email__exact=email)
if not U:
print "%s is an unrecognized user." %message['from']
continue
print "Checking to see if a ticket ID has been given in the subject line."
try:
match = re.findall('ticket-[0-9]*',message['subject'])[0]
ticket_id = match.split('-')[1]
print "Found ticket ID %s." %ticket_id
print "Make sure this is a valid ticket ID."
T = Ticket.objects.get(id=ticket_id)
print "Create a note for the ticket."
N = Note()
N.ticket = T
N.added_by = U
N.updated_by = U
print "Parsing for message body and attachments."
N.comment = ''
attachments = list()
if message.is_multipart():
for part in message.get_payload():
if 'text' == part.get_content_maintype():
N.comment += part.get_payload()
else:
A = Attachment()
A.file = part.get_filename()
A.title = part.get_filename()
A.added_by = U
A.updated_by = U
A.ticket = T
attachments.append(A)
path = '../data/files/attachments/%s' %part.get_filename()
print "Saving attachment to %s" %path
f = open(path,'w')
f.write(part.get_payload(decode=True))
f.close()
print "Saving the attachment info to the database."
A.save()
else:
N.comment = message.get_payload()
print "Save the note."
N.save()
except Exception, error:
print "No ticket ID found."
print "Creating a new ticket."
T = Ticket()
T.created_from = 'email'
T.added_by = U
T.updated_by = U
T.subject = message['subject']
T.site = Config.site
if Config.assign_to: T.assigned_to = Config.assign_to
if Config.set_priority_to: T.priority = Config.set_priority_to
if Config.set_ticket_type_to: T.type = Config.set_ticket_type_to
print "Parsing for message body and attachments."
T.description = ''
attachments = list()
if message.is_multipart():
for part in message.get_payload():
if 'text' == part.get_content_maintype():
T.description += part.get_payload()
else:
A = Attachment()
A.file = part.get_filename()
A.title = part.get_filename()
A.added_by = U
A.updated_by = U
attachments.append(A)
path = '../data/files/attachments/%s' %part.get_filename()
print "Saving attachment to %s" %path
f = open(path,'w')
f.write(part.get_payload(decode=True))
f.close()
else:
T.description = message.get_payload()
print "Save the ticket, then save any attachments."
T.save()
for A in attachments:
A.ticket = T
A.save()
print "Deleting the original message."
Conn.dele(message_id)
message_id += 1
Conn.quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment