We're going to explore a rather special module that will allow us to add a critical functionality to our framework: sending emails, which is ideal for sending emails to an authenticated user in Flask.
We must remember that Flask is a micro-framework, which means it incorporates the minimum functionalities necessary to operate. Therefore, tools that are vital today, such as sending emails, are not included as standard. To meet this need, we will use the Flask-Mail extension.
Flask-Mail allows sending emails through an SMTP client previously configured in the Flask application.
Installation
To obtain this package, we will perform the same process as with previous modules using the pip command:
$ pip install flask-mailThe package is quite lightweight, so the installation will only take a few seconds. Once installed, we can start our application perfectly.
️ Configuration and Initialization
To take the first steps, we must import the module and initialize it with our application instance (app).
from flask_mail import Mail
# ... after declaring the app
mail = Mail(app)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 = TrueWe register the extension globally at the application level:
app\my_app\__init__.py
from flask_mail import Mail
***
mail = Mail()
mail.init_app(app)It is a scheme similar to the one we use with Bootstrap or CSRF protection. By passing the application instance, the module is ready to carry out the configurations.
You must ensure that the app configurations are loaded before initializing the Mail object. If you do it the other way around, you might encounter connection errors, as the module will attempt to connect without knowing the server parameters.
⚙️ Mail Server Parameters
In the configuration file (either in base_config or in your specific environment one), we must define the SMTP server parameters. Here I explain the most important ones:
- MAIL_SERVER: The outgoing server (e.g., smtp.gmail.com or localhost).
- MAIL_PORT: Generally 25, 465, 587, or 2525.
- MAIL_USE_TLS / MAIL_USE_SSL: To encrypt the communication.
- MAIL_USERNAME / MAIL_PASSWORD: Your access credentials.
- MAIL_DEFAULT_SENDER: The email that will appear as the default sender.
- MAIL_SUPPRESS_SEND: If set to True, emails will not actually be sent. It is ideal for development environments to avoid using up sending quotas.
Testing with Mailtrap
To avoid having to configure a real Gmail server or hiring hosting, we will use Mailtrap, a free service that intercepts outgoing emails and displays them in a virtual inbox.
Once registered in Mailtrap, we select the integration with Flask, and the service will provide us with the server, port, username, and password data that we must paste into our configuration file.
Sending Messages
To send an email, we will use the Message class. We can define the subject, the recipients (as a list), and the body of the message.
1. Basic Message (Text and HTML)
You can send content in plain text using .body or in rich format using .html. If you define both, the email client will prioritize the HTML.
from flask_mail import Message
msg = Message("Hello Flask", recipients=["andres@desarrollolibre.net"])
msg.body = "Hello world in plain text"
msg.html = "<b>Hello world in bold</b>"
mail.send(msg)2. Attaching Files
We can also "attach" files. It is very useful for sending images or documents. We need to open the file in binary mode and use the attach function.
with app.open_resource("static/logo.png") as fp:
msg.attach("logo.png", "image/png", fp.read())3. Customizing the Sender
You can configure the sender more elegantly by passing a tuple instead of just a string, so that a descriptive name appears:
MAIL_DEFAULT_SENDER = ("Andrés from Desarrollo Libre", "andres@email.com")4. Full Code
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 simply text:
msg = Message("Hello", sender=("Me", "me@example.com"))
msg.body = "testing"
I agree to receive announcements of interest about this Blog.
Flask Mail allows you to send emails with HTML using a pre-configured SMTP client in the Flask application; let's see how to install, configure, and use the package.