mail.send_message flask not working, SSL ==> 465
Import necessary modules:
python from flask import Flask, render_template, request from flask_mail import Mail, Message
Create an instance of Flask and configure email settings: ```python app = Flask(name)
app.config['MAIL_SERVER'] = 'smtp.example.com' # Replace with SMTP server app.config['MAIL_PORT'] = 465 # SSL port for email sending app.config['MAIL_USERNAME'] = '[email protected]' # Your email address app.config['MAIL_PASSWORD'] = 'your_password' # Your email password app.config['MAIL_USE_TLS'] = False app.config['MAIL_USE_SSL'] = True ```
Initialize Flask-Mail with the Flask app:
python mail = Mail(app)
Create a function to send an email:
python def send_email(subject, recipient, body): msg = Message(subject, sender='[email protected]', # Your email address recipients=[recipient]) # Recipient's email address msg.body = body mail.send(msg)
Use the
send_email
function where needed in your Flask application: ```python @app.route('/send_email', methods=['GET', 'POST']) def send_email_route(): if request.method == 'POST': subject = request.form['subject'] recipient = request.form['recipient'] body = request.form['body']send_email(subject, recipient, body) return 'Email sent successfully!'
return render_template('email_form.html') ```
Create an HTML form (
email_form.html
) to take input for sending an email: ```html
```
- Run the Flask application:
python if __name__ == '__main__': app.run(debug=True)
Explanation:
1. Import necessary modules to use Flask and Flask-Mail for email functionality.
2. Initialize Flask app and configure email settings like SMTP server, port, email credentials, and SSL settings.
3. Initialize Flask-Mail extension with the Flask app to enable email sending.
4. Define a function (send_email
) that constructs an email message and sends it using Flask-Mail.
5. Implement a route in the Flask app (send_email_route
) that handles POST requests containing email data and sends the email using the send_email
function.
6. Create an HTML form (email_form.html
) to take input for the email subject, recipient, and body.
7. Run the Flask application to enable sending emails via the defined routes and functions.