Last active
July 8, 2021 07:00
-
-
Save takwas/f2bc4457de2044049c4561bbbf3f8a3d to your computer and use it in GitHub Desktop.
Flask-Mail Example
This file contains hidden or 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
| import os | |
| from flask import Flask, render_template | |
| from flask_mail import Mail, Message | |
| from lepl.apps.rfc3696 import Email # $ pip install lepl | |
| app = Flask(__name__) | |
| app.config.update({ | |
| 'MAIL_SENDER' : os.environ.get('MAIL_SENDER_EMAIL'), | |
| 'MAIL_SERVER' : 'smtp.mail.yahoo.com', | |
| 'MAIL_PORT' : '587', | |
| 'MAIL_USE_TLS' : 'True', | |
| 'MAIL_USE_SSL' : 'False', | |
| 'MAIL_USERNAME' : os.environ.get('MAIL_USERNAME'), | |
| 'MAIL_PASSWORD' : os.environ.get('MAIL_PASSWORD')}) | |
| # Instantiate Flask-Mail Flask extension | |
| mailer = Mail(app) | |
| # email address format validator | |
| validator = Email() | |
| def validate_email(email): | |
| if validator(email): | |
| return email | |
| def send_email(app, recipients, message, sender=None, subject="Hello there!"): | |
| # if `recipients`is passed as a string or unicode, | |
| # replace commas and/or semi-colons with | |
| # whitespaces and split (around the whitespaces) | |
| # the string into a list of recipients | |
| if isinstance(recipients, basestring): | |
| recipients = recipients.replace(',', ' ').replace(';', ' ').split() | |
| recipients = [email for email in recipients.split() if | |
| validate_email(email) is not None] | |
| if sender is None: | |
| sender = app.config.get('MAIL_SENDER') | |
| try: | |
| mail_msg = Message( | |
| subject=subject, | |
| recipients=recipients, | |
| html=message, | |
| sender=sender | |
| ) | |
| mailer.send(mail_msg) | |
| return True | |
| except: | |
| print 'Error formatting and sending email!' # DEBUG | |
| return False | |
| def format_msg_html(): | |
| # ... | |
| return render_template('email_html.html') | |
| @app.route('/registration-complete', methods=['GET', 'POST']) | |
| def on_signup_success(): | |
| # ... User signup completed | |
| send_email(app, ['me@you.us'], format_msg_html()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment