Un script en Python qui permet de convertir un email (message texte) au format HTML, afin par exemple de le sauvegarder en tant que page web.
#!/usr/bin/env python
__author__ = 'Steve Purcell <stephen_purcell at yahoo dot com>'
import rfc822, mimetools, multifile, sys, string
from cgi import escape
class Formatter:
def __init__(self, instream, outstream, extraheaders=()):
self.outstream = outstream
self.extraheaders = extraheaders
self._format(mimetools.Message(instream))
def _format(self, msg):
self._format_headers(msg)
self._format_body(msg)
def _format_headers(self, headers):
subject = escape(headers['subject'])
sender = escape(headers['from'])
sent_to = headers.get('to', None)
date = escape(headers['date'])
cc_to = headers.get('cc', None)
self.outstream.write('''\
<html><head>
<title>%(subject)s</title>
</head><body bgcolor="#ffffff">
<h1>%(subject)s</h1>
<b>Date:</b> %(date)s<br>
<b>From:</b> %(sender)s<br>
''' % locals())
if sent_to:
sent_to = escape(sent_to)
self.outstream.write("<b>To:</b> %(sent_to)s<br>\n" % locals())
if cc_to:
cc_to = escape(cc_to)
self.outstream.write("<b>CC:</b> %(cc_to)s<br>\n" % locals())
for header in self.extraheaders:
header_value = headers.get(header,None)
if header_value:
header_value = escape(header_value)
header_name = string.join(map(string.capitalize,
string.split(header,'-')),'-')
self.outstream.write("<b>%s</b>: %s<br>" %
(header_name, header_value))
self.outstream.write("<hr noshade size=1>\n")
def _format_body(self, msg):
content_type = msg.pe()
is_html = (content_type == 'text/html')
input = msg.fp
if not is_html:
self.outstream.write("<pre>\n")
while 1:
line = input.readline()
if not line:
break
if not is_html:
line = escape(line)
self.outstream.write(line)
if not is_html:
self.outstream.write("</pre>\n")
self.outstream.write("</body></html>")
if __name__ == '__main__':
Formatter(sys.stdin, sys.stdout, ('organization','x-mailer'))
|