DEV Community

Cover image for How to send emails while using Python Flask fully asynchronously ?
Aniket Sarkar
Aniket Sarkar

Posted on

How to send emails while using Python Flask fully asynchronously ?




Introduction

Sending emails is one of the important work of Flask micro web framework. Now a days people are using the old and unmaintained module Flask-Mail to send emails. Flask-Mail is totally dead now. This is time to shift or migrate to Flask-Mailing module to send emails fully asynchronously(The new Flask-2.0 has the asynchronous support). Flask-Mailing module internally using the aiosmtplib lib to provide the asynchronous SMTP connection.


Github Repo: https://github.com/marktennyson/flask-mailing πŸ”±
Official Documentation: https://marktennyson.github.io/flask-mailing/ πŸ”Ά

Key features of the Flask-Mailing module:

  • ➿ Fully asynchronous support for email sending.
  • πŸ“€ sending emails with either with Flask or using asyncio module.
  • ⚜️ Able to perform any TLS of SSL based encryption.
  • βš”οΈ sending files either from form-data or files from server.
  • πŸ—žοΈ Using Jinja2 HTML Templates.
  • 🩹 email utils (utility allows you to check temporary email addresses, you can block any email or domain).
  • 🧲 email utils has two available classes DefaultChecker and WhoIsXmlApi.

More information will be available at the Getting-Started section. πŸ˜€

❀️ Configure Flask-Mailing with a simple Flask application:

  • πŸ‘‹ install or update the Flask-Mailing module on your machine from PYPI using PIP
pip install -U flask-mailing
Enter fullscreen mode Exit fullscreen mode
  • πŸ§›β€β™€οΈ Create a simple flask application, like this:
from flask import Flask

app= Flask(__name__)

@app.route("/")
def index():
    return "hello from Pluto."

if __name__ == "__main__":
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode
  • ⛹️‍♀️ Now import the Mail and Message class from flask-mailing and set the app's default config variable:
from flask_mailing import Mail, Message

app.config['MAIL_USERNAME'] = "your-email@your-domain.com"
app.config['MAIL_PASSWORD'] = "world_top_secret_password"
app.config['MAIL_PORT'] = 587
app.config['MAIL_SERVER'] = "your-email-server.com"
app.config['MAIL_TLS'] = True
app.config['MAIL_SSL'] = False

mail = Mail(app)
Enter fullscreen mode Exit fullscreen mode
  • πŸ‹οΈβ€β™€οΈ Now configure a route to initialize the Message class to create a message instance.
@app.get("/email")
async def simple_send():

    message = Message(
        subject="Flask-Mailing module",
        recipients=["aniketsarkar@yahoo.com"],
        body="This is the basic email body",
        )
    await mail.send_message(message)
    return jsonify(status_code=200, content={"message": "email has been sent"})
Enter fullscreen mode Exit fullscreen mode
  • 🐻 Here is the complete example for better understanding of the working procedure:
from flask import Flask, jsonify
from flask_mailing import Mail, Message

mail = Mail()

def create_app():
    app = Flask(__name__)


    app.config['MAIL_USERNAME'] = "your-email@your-domain.com"
    app.config['MAIL_PASSWORD'] = "world_top_secret_password"
    app.config['MAIL_PORT'] = 587
    app.config['MAIL_SERVER'] = "your-email-server.com"
    app.config['MAIL_TLS'] = True
    app.config['MAIL_SSL'] = False
    mail.init_app(app)

    return app

#send a simple email using flask_mailing module.

app = create_app()

@app.get("/email")
async def simple_send():

    message = Message(
        subject="Flask-Mailing module",
        recipients=["aniketsarkar@yahoo.com"],
        body="This is the basic email body",
        )


    await mail.send_message(message)
    return jsonify(status_code=200, content={"message": "email has been sent"})
Enter fullscreen mode Exit fullscreen mode
  • 🐼 For more example plese click here

Support πŸ˜‡:

I have created some more python Flask extensions including Flask-Express, to support the Flask as well as the Python community.
If you find this project to be useful then you can support me using the Buy Me a Coffee link below so I can continue chasing my dream of building useful Projects that will help the Python developer community and the general audience and will allow me to change my life as well πŸ˜‡

buy me a coffee ❀️

Paytm

UPI: aniketsarkar@ybl

Special Note πŸ”΄

If you would like to use Django's email implementation, you should probably go with waynerv's Flask-Mailman package.

Please give a star to the Github Repo of Flask-Mailing. It will help to reach out to many users


Feel free to Like and Share this post πŸ˜‡

Share your feedback by Commenting below πŸ’¬

Drop me a Follow for more Awesome content related to Web Development and Programming πŸ™Œ

Thank you for your support ❀️

Top comments (1)

Collapse
 
vivek_gupta_796e6eac02264 profile image
vivek gupta

I Tried to use flask_email to send otp
and provided configuration as:
MAIL_SERVER = "smtp.gmail.com"
MAIL_PORT = "465"
MAIL_USERNAME = "validemail@gmail.com"
MAIL_PASSWORD = "dummypassword"

I am facing issues where the smtp server is able to send email to @gmail and @edu accounts without any errors. But I cannot see email in my edu account from validemail@gmail.com.

I cannot think about what is wrong or what needs to be done.
can somebody please help?