Created
April 9, 2010 02:50
-
-
Save jlongster/360839 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### Parsing | |
import sys | |
import uuid | |
import os | |
import subprocess | |
from os.path import join | |
from send import send_files | |
tmp_dir = '/service/posterous/tmp' | |
def make_bucket(): | |
path = join(tmp_dir, str(uuid.uuid1())) | |
os.mkdir(path) | |
os.mkdir(join(path, "new")) | |
return path | |
def new_files(bucket): | |
path = join(bucket, 'new') | |
files = os.listdir(path) | |
files.sort() | |
return map(lambda x: join(path, x), files) | |
def handle_pdf(bucket, filename): | |
(root, ext) = os.path.splitext(filename) | |
subprocess.call(['convert', | |
join(bucket, filename), | |
join(bucket, 'new', '%s-%%03d.png' % root)]) | |
handlers = { | |
"application/pdf": handle_pdf | |
} | |
def authenticate(name): | |
# This still isn't very secure, in the future check IP | |
return (name.find('[email protected]') != -1 or | |
name.find('[email protected]') != -1) | |
### Sending | |
from email.MIMEMultipart import MIMEMultipart | |
from email.Utils import formatdate | |
from email.MIMEText import MIMEText | |
from email.MIMEBase import MIMEBase | |
from email import Encoders | |
import os | |
def send_files(to, subject, txt=None, files=None): | |
msg = MIMEMultipart() | |
msg['From'] = '[email protected]' | |
msg['To'] = to | |
msg['Date'] = formatdate(localtime=True) | |
msg['Subject'] = subject | |
if msg: | |
msg.attach(MIMEText(txt)) | |
if files: | |
for f in files: | |
part = MIMEBase('application', 'octet-stream') | |
part.set_payload(open(f, 'rb').read()) | |
Encoders.encode_base64(part) | |
part.add_header('Content-Disposition', | |
'attachment; filename="%s"' | |
% os.path.basename(f)) | |
msg.attach(part) | |
s = smtplib.SMTP('smtp.gmail.com', 587) | |
s.ehlo() | |
s.starttls() | |
s.login('[email protected]', '<pass>') | |
s.sendmail('[email protected]', to, msg.as_string()) | |
s.quit() | |
### Main | |
msg = email.message_from_file(sys.stdin) | |
if msg.is_multipart() and authenticate(msg.get('From')): | |
txt = '' | |
to = '[email protected]' | |
bucket = make_bucket() | |
for part in msg.walk(): | |
if part.get_content_type() == 'text/plain': | |
txt = part.get_payload().strip() | |
elif part.get_filename(): | |
filename = part.get_filename() | |
f = open(join(bucket, filename), 'wb') | |
f.write(part.get_payload(decode=True)) | |
f.close() | |
handlers[part.get_content_type()](bucket, filename) | |
send_files(to, msg.get('Subject'), txt, new_files(bucket)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment