How do I Send Email from My Flask App on Linode?
I have a Flask app in a local environment that sends email without an issue. Now that I've deployed it to a Linode instance, I'm unable to get it to send mail successfully.
1 Reply
Configure Your Flask App
I've been able to get my app to send email using Gmail with the following setup. If you're using a different email service these configs should still be helpful, however, you'll probably need to make a few changes.
In order to get your Flask App to send mail, most importantly, you'll need to make sure the SMTP ports on your instance are not restricted. If they are, you can always reach out to the Support Team to request the restrictions be lifted.
Next, ensure you've got the flask-mail
module installed:
$ pip3 install flask-mail
Import the module to your file and configure the flask mail options in your app like this:
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = False
app.config['MAIL_USERNAME'] = 'your-email@gmail.com'
app.config['MAIL_PASSWORD'] = '<your gmail app password>'
For full flask mail configurations including message and recipient configurations, refer to the official documentation.
You can find instructions for retrieving a Gmail app password here. App passwords aren't recommended in most cases, however, they are necessary for uses such as this. Additionally, they can only be used when you have 2FA enabled for your account.
Once you have these settings in place, you'll be able send email using your Flask app! In case you need an additional reference, you can check out my full app configs here.
Going Further
To round out this guide, there are a few final suggestions I want to make. The first is to institute logging for your app. The Marketplace Flask deployment comes with Supervisor. You may want to configure that service to write logs for your application.
The second is to set up an Nginx reverse proxy so that your application can be served to the internet.
And, as always, we suggest securing your instance to help protect against unwanted logins.
Deploy Flask
Finally, I wanted to add resources for someone to deploy Flask from start to finish, in case they don't have a Flask instance on Linode already. The easiest way to get Flask up and running with is by deploying the Flask app from the Linode Marketplace.