Send an E-mail in Python Flask
Flask-Mail is an extension for Flask used to send emails from your Flask application.It provides a simple interface to send email messages with html format and attachments. The following example shows, how to send Email from your Gmail with Flask-Mail
in Python Flask
First, we have to install Flask-Mail extension
pip install Flask-Mail
Next, Change following settings in your Gmail
and Account
i) Gmail->Settings->Forwarding and POP/IMAP->Enable IMAP ii) Create an app password. Click here to how to create app password
Configure the following Settings in Flask-Mail
app.config["DEBUG"]=False app.config["TESTING"]=False app.config["SQLALCHEMY_TRACK_MODIFICATIONS"]=False app.config["SECRET_KEY"]="sekret_key" app.config["MAIL_SERVER"]="smtp.gmail.com'" app.config["MAIL_PORT"]=465 app.config["MAIL_USE_TLS"]=False app.config["MAIL_USE_SSL"]=True app.config["MAIL_DEBUG"]=False app.config["MAIL_USERNAME"]="your_username@gmail.com" app.config["MAIL_PASSWORD"]="your_app_password" app.config["MAIL_DEFAULT_SENDER"]=None app.config["MAIL_MAX_EMAILS"]=None app.config["MAIL_SUPPRESS_SEND"]=False app.config["MAIL_ASCII_ATTACHMENTS"]=False
Example
from flask import Flask,render_template from flask_mail import Mail,Message import smtplib app = Flask(__name__) app.config.update( DEBUG=True, #EMAIL SETTINGS MAIL_SERVER='smtp.gmail.com', MAIL_PORT=465, MAIL_USE_SSL=True, MAIL_USERNAME = 'from@gmail.com', MAIL_PASSWORD = 'password' ) mail = Mail(app) @app.route("/") def home(): try: msg = Message("Message Title Here", sender="from@gmail.com", recipients=["to@gmail.com"]) msg.body = "Sample Message Body Here" msg.html = "<h1 style='color:green;'>Sample Message Body Here With HTML and CSS Style</h1>" with app.open_resource("path/sample.pdf") as fp: msg.attach("sample.pdf", "application/pdf", fp.read()) mail.send(msg) return 'Mail Send Successfully' except Exception as e: print(str(e)) return "" if __name__=="__main__": app.run(debug=True)
Run the Project:
- Run 'app.py' file.
- Browse the URL 'localhost:5000'.