Skip to content

Instantly share code, notes, and snippets.

@mikaelhg
Created October 14, 2011 10:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mikaelhg/1286761 to your computer and use it in GitHub Desktop.
Save mikaelhg/1286761 to your computer and use it in GitHub Desktop.
PostgreSQL PL/Python stored procedures for email handling
CREATE OR REPLACE FUNCTION download(url TEXT) RETURNS TEXT
AS $$
import urllib2
try:
result = urllib2.urlopen(url)
rawdata = result.read()
info = result.info()
try:
content_type, encoding = info['Content-Type'].split('charset=')
except:
import chardet
encoding = chardet.detect(rawdata)['encoding']
return rawdata.decode(encoding)
except urllib2.URLError, e:
plpy.error(e)
return ''
$$ LANGUAGE plpythonu;
CREATE OR REPLACE FUNCTION mime_subject(mime_text TEXT) RETURNS TEXT
AS $$
import email
try:
msg = email.message_from_string(mime_text)
subject = msg['Subject']
return subject
except Exception, e:
plpy.info(e)
return ''
$$ LANGUAGE plpythonu;
CREATE OR REPLACE FUNCTION mime_subject(mime_text TEXT) RETURNS TEXT
AS $$
import email
from email.header import decode_header
try:
msg = email.message_from_string(mime_text)
subject = msg['Subject']
decodes = decode_header(subject)
if len(decodes) == 1:
str, encoding = decodes[0]
if encoding:
return str.decode(encoding)
return subject
except Exception, e:
plpy.info(e)
return ''
$$ LANGUAGE plpythonu;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment