Skip to content

Instantly share code, notes, and snippets.

Created June 27, 2014 15:03
Show Gist options
  • Save rkz/e60e3b86e1ac8b9806e0 to your computer and use it in GitHub Desktop.
Save rkz/e60e3b86e1ac8b9806e0 to your computer and use it in GitHub Desktop.
Mail functions for Flask (SMTP settings and e-mail activation in the app's config + rendering a Jinja template as content)
# -*- coding: utf-8 -*-
import smtplib
from email.mime.text import MIMEText
from . import app
def send(recipients, subject, body):
# Destination override
if app.config['EMAIL_TO']:'Original email recipients {} overriden to {}'
.format(recipients, app.config['EMAIL_TO']))
recipients = app.config['EMAIL_TO']
msg = MIMEText(body, 'html', 'utf-8')
msg['Subject'] = subject
msg['From'] = app.config['EMAIL_FROM']
msg['To'] = ','.join(recipients)
msg['Cc'] = app.config['EMAIL_CC'] if app.config['EMAIL_CC'] else ''
msg['Bcc'] = app.config['EMAIL_BCC'] if app.config['EMAIL_BCC'] else ''
if app.config['EMAIL_ENABLED']:
s = smtplib.SMTP(app.config['SMTP_HOST'])
if app.config['SMTP_STARTTLS']:
s.login(app.config['SMTP_USER'], app.config['SMTP_PASSWORD'])
s.sendmail(app.config['EMAIL_FROM'], recipients, msg.as_string())
s.quit()'Sent email with subject=[{}] to={} cc={} bcc={}'.format(
msg['Subject'], msg['To'], msg['Cc'], msg['Bcc']
def send_from_template(recipients, subject, template_path, **kwargs):
template = app.jinja_env.get_template(template_path)
body = template.render(**kwargs)
return send(recipients, subject, body)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment