DEV Community

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

Posted on

2 2

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 โค๏ธ

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

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?

Hot sauce if you're wrong - web dev trivia for staff engineers

Hot sauce if you're wrong ยท web dev trivia for staff engineers (Chris vs Jeremy, Leet Heat S1.E4)

  • Shipping Fast: Test your knowledge of deployment strategies and techniques
  • Authentication: Prove you know your OAuth from your JWT
  • CSS: Demonstrate your styling expertise under pressure
  • Acronyms: Decode the alphabet soup of web development
  • Accessibility: Show your commitment to building for everyone

Contestants must answer rapid-fire questions across the full stack of modern web development. Get it right, earn points. Get it wrong? The spice level goes up!

Watch Video ๐ŸŒถ๏ธ๐Ÿ”ฅ

๐Ÿ‘‹ Kindness is contagious

If you found this post useful, consider leaving a โค๏ธ or a nice comment!

Got it