scripts/gestion/mail/mail.py
2013-10-26 19:20:38 +02:00

98 lines
4.1 KiB
Python

#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import jinja2
import sys
from email.header import Header
from email.message import Message
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.Utils import formatdate
from markdown import markdown
sys.path.append('/usr/scripts/')
from gestion.email_tools import format_sender
sys.path.pop()
default_language = 'fr'
template_path = '/usr/scripts/gestion/mail/template/'
html_template = template_path + 'html'
html_mutilang_template = template_path + 'html_multilang'
text_mutilang_template = template_path + 'text_multilang'
templateLoader = jinja2.FileSystemLoader( searchpath=["/", template_path] )
templateEnv = jinja2.Environment( loader=templateLoader )
# file extension to rendering function map
markup = {
'md' : markdown,
}
### For an example:
### print generate('bienvenue', {'From':'respbats@crans.org', 'To':'admin@genua.fr', 'lang_info':'English version below'}).as_string()
def submessage(playload, type, charset='utf-8'):
"""Renvois un sous message à mettre dans un message multipart"""
submsg=MIMEText('', type, charset)
del(submsg['Content-Transfer-Encoding'])
submsg['Content-Transfer-Encoding']='8bit'
submsg.set_payload(playload)
return submsg
def get_lang(mail, part, lang, lang_fallback):
for l in [lang, lang_fallback]:
for ext in markup.keys():
if os.path.isfile(template_path + mail + '/' + part + '/' + l + '.' + ext):
return l, ext, template_path + mail + '/' + part + '/' + l + '.' + ext
if os.path.isfile(template_path + mail + '/' + part + '/' + l):
return l, None, template_path + mail + '/' + part + '/' + l
raise ValueError("Language %s nor %s found" % (lang, lang_fallback))
def body(mail, lang1, lang2, mk, params, charset):
file1 = template_path + mail + '/body/' + lang1
file2 = template_path + mail + '/body/' + lang2
if mk:
file1 = file1 + '.' + mk
file2 = file2 + '.' + mk
if lang1 == lang2 or not os.path.isfile(file2): # No alt language
txt = templateEnv.get_template(file1).render(params)
ret = [ submessage(txt.encode(charset), 'plain', charset) ]
if mk: # compute the html version
html = templateEnv.get_template(html_template).render({'body': markup[mk](txt)})
ret.append(submessage(html.encode(charset), 'html', charset))
else:
txt1 = templateEnv.get_template(file1).render(params)
txt2 = templateEnv.get_template(file2).render(params)
params_txt=dict(params)
params_txt.update({'body1': txt1, 'body2':txt2})
txt = templateEnv.get_template(text_mutilang_template).render(params_txt)
ret=[ submessage(txt.encode(charset), 'plain', charset) ]
if mk: # compute the html version
params_html=dict(params)
params_html.update({'lang1':lang1, 'lang2':lang2, 'body1': markup[mk](txt1), 'body2': markup[mk](txt2)})
html = templateEnv.get_template(html_mutilang_template).render(params_html)
ret.append(submessage(html.encode(charset), 'html', charset))
return ret
def generate(mail, params, lang=default_language, lang_fallback=default_language, lang_alt='en', charset='utf-8'):
"""Génère un message multipart"""
msg = MIMEMultipart('alternative')
if os.path.isdir(template_path + mail):
for filename in [dir for dir in os.listdir(template_path + mail) if os.path.isdir(template_path + mail + '/' + dir)]:
lang_tmp, mk, file = get_lang(mail, filename, lang, lang_fallback)
if filename == 'body':
for part in body(mail, lang_tmp, lang_alt, mk, params, charset):
msg.attach(part)
else:
txt = templateEnv.get_template(file).render(params)
if filename in ['From', 'To', 'Cc', 'Bcc']:
msg[filename] = format_sender(txt, charset)
else:
msg[filename]=Header(txt.encode(charset), charset)
msg['Date']=formatdate(localtime=True)
return msg