flask uses Flask-Mail to send emails

Flask-Mail can send emails and can be integrated with Flask, allowing us to implement this function more conveniently.

1. Installation

Install using pip:

$ pip install Flask-Mail

Or download the source code to install:

$ git clone https://github.com/mattupstate/flask-mail.git
$ cd flask-mail
$ python setup.py install

2. Send email

Flask-Mail connects to the Simple Mail Transfer Protocol (SMTP) server and hands the email to this server for sending. Here we take QQ mailbox as an example to introduce how to simply send emails. Before that, we need to know what the server address and port of QQ mailbox are

# -*- coding: utf-8 -*-
from flask import Flask
from flask_mail import Mail, Message
import os
app = Flask(__name__)
app.config['MAIL_SERVER'] = 'smtp.qq.com'  # 邮件服务器地址
app.config['MAIL_PORT'] = 25               # 邮件服务器端口
app.config['MAIL_USE_TLS'] = True          # 启用 TLS
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME') or '[email protected]'
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD') or '123456'
mail = Mail(app)
@app.route('/')
def index():
    msg = Message('Hi', sender='[email protected]', recipients=['[email protected]'])
    msg.html = '<b>Hello Web</b>'
    # msg.body = 'The first email!'
    mail.send(msg)
    return '<h1>OK!</h1>'
if __name__ == '__main__':
    app.run(host='127.0.0.1', debug=True)

Before sending, you need to set the username and password. Of course, you can also write them directly in the file. If you are reading from environment variables, you can do this:

$ export MAIL_USERNAME='[email protected]'
$ export MAIL_PASSWORD='123456'

Change the above sender and recipients and you can test it.

From the above code, we can know that sending emails using Flask-Mail mainly involves the following steps:

  • Configure the mail server address, port, username and password of the app object, etc.
  • Create an instance of Mail: mail = Mail(app)
  • Create a Message message instance with three parameters: email title, sender and receiver
  • Create the email content, if it is in HTML format, use msg.html, if it is in plain text format, use msg.body
  • Finally call mail.send(msg) to send the message

Flask-Mail configuration items
Flask-Mail uses the standard Flask configuration API for configuration. The following are some commonly used configuration items:
Insert image description here

3. Send emails asynchronously

If you use the above method to send an email, you will find that the page freezes for a few seconds before the message appears. This is because we use a synchronization method. In order to avoid delays in sending emails, we move the task of sending emails to a background thread. The code is as follows:

# -*- coding: utf-8 -*-
from flask import Flask
from flask_mail import Mail, Message
from threading import Thread
import os
app = Flask(__name__)
app.config['MAIL_SERVER'] = 'smtp.qq.com'
app.config['MAIL_PORT'] = 25
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME') or 'smtp.example.com'
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD') or '123456'
mail = Mail(app)
def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)
@app.route('/sync')
def send_email():
    msg = Message('Hi', sender='[email protected]', recipients=['[email protected]'])
    msg.html = '<b>send email asynchronously</b>'
    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()
    return 'send successfully'
if __name__ == '__main__':
    app.run(host='127.0.0.1', debug=True)

Above, we created a thread and performed the task send_async_email. The implementation of this task involves a problem:

Many Flask extensions assume that an active program context and request context already exist. The send() function in Flask-Mail uses current_app, so the program context must be activated. However, when executing the mail.send() function in different threads, the program context must be manually created using app.app_context().

4. Emails with attachments

Sometimes, when we send an email, we need to add attachments, such as documents and pictures. This is also very simple. The code is as follows:

# -*- coding: utf-8 -*-
from flask import Flask
from flask_mail import Mail, Message
import os
app = Flask(__name__)
app.config['MAIL_SERVER'] = 'smtp.qq.com'  # 邮件服务器地址
app.config['MAIL_PORT'] = 25               # 邮件服务器端口
app.config['MAIL_USE_TLS'] = True          # 启用 TLS
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME') or '[email protected]'
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD') or '123456'
mail = Mail(app)
@app.route('/attach')
def add_attchments():
    msg = Message('Hi', sender='[email protected]', recipients=['[email protected]'])
    msg.html = '<b>Hello Web</b>'
    with app.open_resource("/Users/Admin/Documents/pixel-example.jpg") as fp:
        msg.attach("photo.jpg", "image/jpeg", fp.read())
    mail.send(msg)
    return '<h1>OK!</h1>'
if __name__ == '__main__':
    app.run(host='127.0.0.1', debug=True)

In the above code, we open a picture on the local machine through app.open_resource(path_of_attachment), and then add the attachment content to the Message object through the msg.attach() method. The first parameter of the msg.attach() method is the file name of the attachment, the second parameter is the MIME (Multipurpose Internet Mail Extensions) type of the file content, and the third parameter is the file content.

5. Send in batches

In some cases, we need to send emails in batches, such as sending password-changing emails to all registered users of the website. In order to avoid having to create and close a connection with the server every time we send an email, our code needs to do some things. Adjust, similar to the following:

with mail.connect() as conn:
    for user in users:
        subject = "hello, %s" % user.name
        msg = Message(recipients=[user.email], body='...', subject=subject)
        conn.send(msg)

The above method of working keeps the application connected to the email server until all emails have been sent. Some mail servers will limit the upper limit of emails sent in one connection. In this case, you can configure MAIL_MAX_EMAILS.

Guess you like

Origin blog.csdn.net/javascript_good/article/details/132687577