Flask Mail to send emails

- Andrés Cruz

En español

Flask Mail to send emails

Flask Mail allows you to send emails using an SMTP client previously configured in the Flask application; to install the package, we have:

$ pip install flask-mail

We will configure the SMTP server to which we are going to connect in the configuration file:

app\my_app\config.py

class DevConfig(Config): 
    MAIL_SERVER = 'localhost' 
    MAIL_PORT = 25 
    MAIL_USERNAME = 'username' 
    MAIL_PASSWORD = 'password' 

And in development mode, we also enable:

app\my_app\config.py

class DevConfig(Config):
    ***
    MAIL_DEBUG = True
    MAIL_SUPPRESS_SEND = False
    TESTING = True

We register the extension globally at the application level:

app\my_app\__init__.py

from flask_mail import Mail
***
mail = Mail()
mail.init_app(app)

You can use the following code as a reference to send emails according to the configurations made previously:

from flask_mail import Message
from my_app import mail

def send_email():
    msg = Message(body="Text Example", 
                  sender="no-reply@MyWeb.net",
                  recipients=["andres@gmail.com"], subject="Subject")
    try:
        print(mail.send(msg))
    except Exception as e:
        print(e)

If you want to define HTML content:

msg = Message("Hello", sender=("Me", "me@example.com"))
msg.html = "<b>testing</b>"

Or just text:

msg = Message("Hello", sender=("Me", "me@example.com"))
msg.body = "testing"

You can get more information at:

https://pythonhosted.org/Flask-Mail/

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.