Home  >  Article  >  Backend Development  >  How to send email using Flask-Mail

How to send email using Flask-Mail

WBOY
WBOYOriginal
2023-08-02 10:17:091013browse

How to use Flask-Mail to send emails

With the development of the Internet, email has become an important tool for people to communicate. When developing web applications, sometimes we need to send emails in specific scenarios, such as sending a welcome email after a user successfully registers, or sending a password reset email when a user forgets their password, etc. Flask is a simple and flexible Python Web framework, and Flask-Mail is an extension library for sending emails under the Flask framework. This article will introduce how to use Flask-Mail to send emails.

First, before using Flask-Mail, we need to install the Flask-Mail library. Use the following command on the command line to install:

pip install Flask-Mail

After the installation is complete, we need to configure the relevant information of the mail server in the Flask application, such as the address, port, user name, password, etc. of the mail server. Normally, we can configure it in the configuration file of the Flask application. The following is an example configuration file:

# 邮件服务器配置
MAIL_SERVER = 'smtp.exmail.qq.com'
MAIL_PORT = 465
MAIL_USE_SSL = True
MAIL_USERNAME = 'your_email@example.com'
MAIL_PASSWORD = 'your_password'
MAIL_DEFAULT_SENDER = 'your_email@example.com'

After having the configuration file, we need to load the configuration in the Flask application. The following is an example of a simple Flask application:

from flask import Flask
from flask_mail import Mail

app = Flask(__name__)
app.config.from_pyfile('config.cfg')

# 初始化Flask-Mail
mail = Mail(app)

@app.route('/')
def index():
    # 发送邮件
    mail.send_message(subject='Hello',
                      body='This is a test email.',
                      recipients=['recipient@example.com'])
    return 'Email sent!'

if __name__ == '__main__':
    app.run()

In the above example, we first imported the Flask-Mail library by from flask_mail import Mail and created a Mail instancemail. Then the mail.send_message() method is called in the view function of app.route('/') to send an email. send_message()The method accepts three parameters, which are the email subject, email body and recipient list. We can adjust them according to actual needs.

In addition to the send_message() method, Flask-Mail also provides other methods to send emails, such as the send() method for sending simple emails, The send_template() method is used to send emails based on templates. Building on the above example, we can expand further.

In actual projects, we may also need to handle some special situations, such as error handling when email delivery fails. For this purpose, Flask-Mail also provides some configuration items. The following are some commonly used configuration items:

  • MAIL_FAIL_SILENTLY: If set to True, no exception will be thrown when sending mail fails. The default is False.
  • MAIL_DEBUG: If set to True, mail-related debugging information will be output on the console. The default is False.
  • MAIL_SUPPRESS_SEND: If set to True, the email will not be actually sent, but will be written to the log file. The default is False.

If we want to handle errors when sending emails fails, we can add a try-except statement after the mail.send_message() method call to catch the exception. The following is an example:

try:
    mail.send_message(subject='Hello',
                      body='This is a test email.',
                      recipients=['recipient@example.com'])
    return 'Email sent!'
except Exception as e:
    return str(e)

Based on the above example, we can customize it as needed to achieve more complex email sending functions.

To summarize, sending emails using Flask-Mail is very simple. We only need to make some configurations in the Flask application and call the methods provided by Flask-Mail to complete the email sending. Flask-Mail not only provides a method for sending simple emails, but also supports sending emails based on templates. It also has rich configuration items and error handling mechanisms, which facilitates us to implement email functions. I hope this article can help you, and I hope you can easily use Flask-Mail to send emails when developing web applications.

The above is the detailed content of How to send email using Flask-Mail. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn