How to config your flask for gmail
To configure Flask for Gmail, follow these steps:
- Import the necessary modules:
- Import the
Flask
class from theflask
module. Import the
flask_mail
extension from theflask_mail
module.Create an instance of the Flask application:
Use the
Flask(__name__)
constructor to create an instance of the Flask application.Configure the Mail settings:
- Set the
MAIL_SERVER
configuration variable to"smtp.gmail.com"
. - Set the
MAIL_PORT
configuration variable to587
. - Set the
MAIL_USE_TLS
configuration variable toTrue
. - Set the
MAIL_USERNAME
configuration variable to your Gmail email address. Set the
MAIL_PASSWORD
configuration variable to your Gmail password or an app password if you have two-factor authentication enabled.Initialize the Mail extension:
- Create an instance of the
Mail
class and pass the Flask application instance as an argument. Use the
mail.init_app(app)
method to initialize the Mail extension.Send an email:
- Create a route in your Flask application to handle sending emails.
- Inside the route, create a message using the
Message
class from theflask_mail
module. - Set the
recipients
attribute of the message to the email address you want to send the email to. - Set the
subject
attribute of the message to the subject of the email. - Set the
body
attribute of the message to the body of the email. - Use the
mail.send(message)
method to send the email.
Please note that you may need to enable "Less Secure Apps" in your Gmail account settings or generate an app password if you have two-factor authentication enabled.