[파이썬] Flask-Mail 확장

Flask-Mail is a popular extension for Flask, a microframework for Python, that allows you to send emails easily and efficiently. It provides a simple and intuitive interface for integrating email functionality into your Flask applications.

In this blog post, we will explore the basics of Flask-Mail and how to use it to send emails from your Flask application.

Installation

To start using Flask-Mail, you need to install it first. You can install it using pip, the Python package installer, by running the following command:

pip install Flask-Mail

Configuration

Once you have Flask-Mail installed, you need to configure it in your Flask application. Flask-Mail requires you to provide the necessary configuration settings, such as the email server, port, username, password, etc. These settings should be specified in your Flask application’s configuration file.

Here is an example of how you can configure Flask-Mail in your Flask application:

from flask import Flask
from flask_mail import Mail

app = Flask(__name__)
app.config['MAIL_SERVER'] = 'smtp.example.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = 'your-email@example.com'
app.config['MAIL_PASSWORD'] = 'your-email-password'

mail = Mail(app)

Sending Emails

With Flask-Mail configured, you can now start sending emails from your Flask application. Flask-Mail provides a simple interface for creating and sending emails.

Here is an example of how to send an email using Flask-Mail:

from flask_mail import Message

# Inside a Flask view function
@app.route('/send-email')
def send_email():
    recipient = 'recipient@example.com'
    subject = 'Example Subject'
    body = 'Hello, this is a test email sent from Flask-Mail!'

    msg = Message(subject=subject, body=body, recipients=[recipient])
    mail.send(msg)

    return 'Email sent successfully!'

In this example, we create a Message object with the subject, body, and recipient(s) of the email. We then use the mail.send() method to send the email.

Conclusion

Flask-Mail is a powerful extension for Flask that makes sending emails from your Flask application a breeze. It provides a simple and intuitive interface for configuring email settings and sending emails.

In this blog post, we covered the basics of Flask-Mail and showed you how to install, configure, and use Flask-Mail to send emails from your Flask application. Now you have the necessary knowledge to easily integrate email functionality into your Flask projects.

Happy sending!