Skip to content

Instantly share code, notes, and snippets.

@slomo
Created January 12, 2012 10:59
Show Gist options
  • Save slomo/1599882 to your computer and use it in GitHub Desktop.
Save slomo/1599882 to your computer and use it in GitHub Desktop.
A script to print a mail delivered on stdin
#!/usr/bin/env python
# could be added to .forward with "|$PATH/mailprint.py"
import sys
import email.feedparser as mailparser
"""
TODO
====
* add quota
* filter for sender / X-Originating-IP
* add more file types
* add printig code
* if possible validate file size
* forward errors to sender (the guy who wants to print)
* log to webpage?
* send mail back? (attention spam!)
* bounce? (not possible as i see it)
* what is about malware? (print me if you dare)
"""
def parse():
parser = mailparser.FeedParser()
for data in sys.stdin:
parser.feed(data)
email = parser.close()
print('Done with parsing')
if email and email.is_multipart():
return email
else:
print('This is either no mime mail, or a mail without attachments')
def process(email):
attachments = {}
to_print = []
valid_content_types = ['application/pdf','text/x-python']
for part in email.get_payload():
# dirty way to test whether this part is a attachment
if part.get_filename() and (part.get_content_type() in valid_content_types):
attachments[part.get_filename()] = part
elif part.get_content_type() == 'text/plain':
to_print = part.get_payload().rsplit('\n')
else:
print('Dropping part of mime-type %s' % part.get_content_type())
for filename in to_print:
if filename in attachments:
print('Would print %s' % filename)
if __name__ == "__main__":
mail = parse()
if mail:
process(mail)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment