# send_html_mail # {{{
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from smtplib import SMTP
import email.Charset
from django.conf import settings
charset='utf-8'
email.Charset.add_charset(charset, email.Charset.SHORTEST, None, None)
def send_html_mail(
subject, sender="no-reply@example.com", recip="", context=None,
html_template="", text_template="", sender_name="",
html_content="", text_content="", recip_list=None, sender_formatted=""
):
if not context: context = {}
if html_template:
html = render(context, html_template)
else: html = html_content
if text_template:
text = render(context, text_template)
else: text = text_content
if not text:
text = html2text(_sanitizeHTML(html,charset))
if not recip_list: recip_list = []
if recip: recip_list.append(recip)
try:
server = SMTP(settings.EMAIL_HOST, settings.EMAIL_PORT)
if settings.EMAIL_HOST_USER and settings.EMAIL_HOST_PASSWORD:
server.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD)
except Exception, e:
print e
return
if not sender_formatted:
sender_formatted = "%s <%s>" % (sender_name, sender)
for recip in recip_list:
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = subject.encode("utf8", 'xmlcharrefreplace')
msgRoot['From'] = sender_formatted.encode("utf8", 'xmlcharrefreplace')
msgRoot['To'] = recip.encode("utf8", 'xmlcharrefreplace')
msgRoot.preamble = 'This is a multi-part message in MIME format.'
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
msgAlternative.attach(MIMEText(smart_str(text), _charset=charset))
msgAlternative.attach(MIMEText(smart_str(html), 'html', _charset=charset))
try:
server.sendmail(sender, recip, msgRoot.as_string())
except Exception, e: print e
server.quit()
def render(context, template):
from django.template import loader, Context
if template:
t = loader.get_template(template)
return t.render(Context(context))
return context
# }}}