Hello we got a message from {{ name }}!
Last active
August 29, 2015 14:24
-
-
Save mariocesar/1e15401dc8dc372bda4c to your computer and use it in GitHub Desktop.
How to send an email in Django, do a basic preflight html optimization for the message, attach documents and attach image inline and also convert markdown to html.
This file contains 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
from crispy_forms.helper import FormHelper | |
from crispy_forms.layout import Layout, Submit, Field, Div | |
from django import forms | |
from .utils import send_mail | |
class ContactForm(forms.Form): | |
name = forms.CharField() | |
email = forms.EmailField() | |
message = forms.CharField(widget=forms.Textarea(), label='Your message') | |
cc = forms.BooleanField(label='Send a copy to yourself', required=False) | |
helper = FormHelper() | |
helper.layout = Layout( | |
Field('name', placeholder='Your name', required=''), | |
Field('email', placeholder='awesome@mailbox.com', required=''), | |
Field('message', placeholder='Hi Humanzilla!', required=''), | |
Div( | |
Div( | |
Submit('submit', 'Send', css_class='button-primary'), | |
css_class='one-half column'), | |
Div( | |
'cc', | |
css_class='one-half column'), | |
css_class='row form-actions' | |
), | |
) | |
def send_mails(self): | |
data = self.cleaned_data | |
context = {} | |
context.update(data) | |
send_mail( | |
subject='Hello from {[name]}'.format(data), | |
template_name='email/contact.md', | |
from_email='alerts@humanzilla.com', | |
recipient_list=['hello@humanzilla.com'], | |
extra_context=context, | |
attachments=None) | |
This file contains 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
from collections import OrderedDict | |
from email.mime.image import MIMEImage | |
import mimetypes | |
import os | |
import xml.etree.ElementTree as ET | |
from django.core.mail import EmailMultiAlternatives | |
from django.template import Context, TemplateDoesNotExist | |
from django.template.loader import get_template | |
from markdown2 import markdown | |
def preflight(content): | |
content = '<body>{}</body>'.format(content) | |
root = ET.fromstring(content) | |
for child in root.iter(): | |
if child.tag in ['p', 'h1', 'h2', 'h3', 'span', 'strong', 'em', 'td', 'th', 'li']: | |
child.set('style', ';'.join([ | |
'font-family: Helvetica, Arial, sans-serif !important', | |
'font-size: 16px !important', | |
'color: #222' | |
])) | |
elif child.tag in ['a']: | |
child.set('style', ';'.join([ | |
'font-family: Helvetica, Arial, sans-serif !important', | |
'font-size: 16px !important', | |
'color: #2DA0E3', | |
'text-decoration: none', | |
])) | |
elif child.tag in ['pre']: | |
child.set('style', ';'.join([ | |
'font-family: Consolas !important', | |
'font-size: 14px !important', | |
'padding: 20px', | |
'background-color: #efefef', | |
'color: #222' | |
])) | |
elif child.tag in ['img']: | |
child.set('border', 0) | |
child.set('style', ';'.join([ | |
'display: block', | |
'outline: none', | |
'-ms-interpolation-mode: bicubic' | |
])) | |
elif child.tag in ['body']: | |
child.set('style', ';'.join([ | |
'margin: 0 !important', | |
'padding: 10px !important', | |
'-webkit-text-size-adjust: 100%', | |
'-ms-text-size-adjust: 100%', | |
])) | |
return ET.tostring(root).decode('utf-8') | |
def send_mail(subject, template_name, from_email, recipient_list, | |
extra_context=None, attachments=None): | |
path, extension = os.path.splitext(template_name) | |
md_template, text_template, html_template = None, None, None | |
try: | |
md_template = get_template('{0}{1}'.format(path, '.md')) | |
except TemplateDoesNotExist: | |
pass | |
try: | |
text_template = get_template('{0}{1}'.format(path, '.txt')) | |
except TemplateDoesNotExist: | |
pass | |
try: | |
html_template = get_template('{0}{1}'.format(path, '.html')) | |
except TemplateDoesNotExist: | |
pass | |
context = dict() | |
context.setdefault('subject', subject) | |
context.setdefault('recipient_list', recipient_list) | |
if extra_context: | |
context.update(extra_context) | |
text_message, html_message = '', '' | |
if md_template: | |
text_message = md_template.render(Context(context)) | |
html_message = markdown(text_message) | |
elif text_template and html_template: | |
text_message = text_template.render(Context(context)) | |
html_message = html_template.render(Context(context)) | |
elif html_template and not text_template: | |
html_message = html_template.render(Context(context)) | |
else: | |
raise TemplateDoesNotExist(template_name) | |
html_message = preflight(html_message) | |
msg = EmailMultiAlternatives(subject, text_message, from_email, recipient_list) | |
msg.attach_alternative(html_message, "text/html") | |
if attachments: | |
for _n, filename in enumerate(attachments, 1): | |
if any(filename.endswith(ext) for ext in ['.png', '.jpg', '.gif']): | |
with open(filename, 'rb') as f: | |
attachment = MIMEImage(f.read()) | |
mimetype, _ = mimetypes.guess_type(filename) | |
attachment.add_header('Content-Disposition', 'inline', name=filename) | |
attachment.add_header('Content-Type', mimetype, name=filename) | |
attachment.add_header('Content-ID', '<img{0}>' % _n) | |
msg.attach(attachment) | |
else: | |
msg.attach_file(filename) | |
msg.send() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment