Mail Extension in Flask
Syntax
from flask_mail import Mail,Message
app = Flask(__name__)
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = 'your.email@gmail.com'
app.config['MAIL_PASSWORD'] = 'yourpassword'
mail = Mail(app)
Example
from flask import Flask
from flask_mail import Mail, Message
app = Flask(__name__)
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = 'your.email@gmail.com'
app.config['MAIL_PASSWORD'] = 'yourpassword'
mail = Mail(app)
@app.route("/")
def index():
msg = Message('Hello', sender='your.email@gmail.com', recipients=['recipient.email@gmail.com'])
msg.body = "Testing Flask Mail Extension"
mail.send(msg)
return "Mail Sent!"
if __name__ == '__main__':
app.run(debug=True, port=5000)
Output
You should receive an email with subject "Hello" and message "Testing Flask Mail Extension" on the recipient email address.
Explanation
The Mail extension in Flask allows you to send emails from your Flask application using a variety of different email servers. In the above example, the extension is configured to use the Gmail SMTP server to send an email with a subject of "Hello" and a body of "Testing Flask Mail Extension" to the recipient email address.
Use
The Mail extension in Flask is useful when you need to send emails from your Flask application. This can be useful for sending notifications, password reset links, or any other type of email communication.
Important Points
- Make sure to configure the Mail extension with the correct SMTP server details and login credentials.
- Use the
Message
class provided by the Mail extension to construct the email message before sending it. - The
send
method of theMail
extension is used to actually send the email.
Summary
The Mail extension in Flask provides an easy-to-use interface for sending emails from your Flask application. By providing the SMTP server details and login credentials, you can quickly send emails to one or more recipients straight from your Flask app.