• Enable the SMTP service of the QQ mailbox
  • Install the Flask E-mail
  • Configuration Flask E-mail
  • Send E-mail
  • A lot of mail
  • The attachment
  • A complete example

It is inevitable to use mailbox authentication in a project. Flask-mail can be used if flask is used.

Flask-mail extension provides a simple interface for configuring SMTP in Flask applications to send Mail messages in views and scripts.

Enable the SMTP service of the QQ mailbox

Here I use THE SMTP service of QQ mailbox, so first need to open the service and obtain the authorization code. Find the position below in “email Settings – Account” of QQ mailbox and enable SMTP service.



After the mobile phone verification of what according to their account Settings, successful verification will get aAuthorization code, this needs to save the subsequent email to send the password filled with this authorization code.

Install the Flask E-mail

pip install Flask-MailCopy the code

Configuration Flask E-mail

Configuration items The default value function
MAIL_SERVER localhost Mailbox server
MAIL_PORT 25 port
MAIL_USE_TLS False Whether to use TLS
MAIL_USE_SSL False Whether to use SSL
MAIL_DEBUG app.debug Whether to print debugging messages in DEBUG mode
MAIL_SUPPRESS_SEND app.testing Sets whether to send the email. True Does not send the email
MAIL_USERNAME None User name, fill in the email
MAIL_PASSWORD None Password, enter the authorization code
MAIL_DEFAULT_SENDER None Default sender, fill in email
MAIL_MAX_EMAILS None The maximum number of messages sent in a connection
MAIL_ASCII_ATTACHMENTS False If MAIL_ASCII_ATTACHMENTS is set to True, the file names are converted to ASCII. Generally used to add attachments.

Mail is managed through a Mail instance:

from flask import Flask
from flask_mail import Mail

app = Flask(__name__)
#...
app.config['MAIL_SERVER'] = 'smtp.qq.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USERNAME'] = '[email protected]'
app.config['MAIL_PASSWORD'] = 'Fill in the Authorization Code'
#...
mail = Mail(app)Copy the code

All messages in this example will be sent using the configuration items passed into the application in the Mail instance.

Or you can set your Mail instance during application configuration by using the init_app method:

mail = Mail()

app = Flask(__name__)
#...
app.config['MAIL_SERVER'] = 'smtp.qq.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USERNAME'] = '[email protected]'
app.config['MAIL_PASSWORD'] = 'Fill in the Authorization Code'
#...
mail.init_app(app)Copy the code

In this example the mail will be sent using the configuration item in Flask’s current_App. This can be useful if you have multiple applications running the same application with different configuration items,

Send E-mail

The first step is to create a Message instance of the content to send the Message:

from flask_mail import Message
msg = Message(subject="Hello World!",
              sender="[email protected]",
              recipients=["[email protected]"])Copy the code

Subject is the mail title. Sender is the sender. If you set “MAIL_DEFAULT_SENDER”, you do not need to enter the sender again. By default, the sender of the configuration item is used. One or multiple recipients can be recipients, or they can be added later.

msg.recipients = ["xxx@qq.com"]
msg.add_recipient("xxxx@qq.com")Copy the code

If sender is a binary, it will be split into name and email address:

msg = Message("Hello",
              sender=("Me"."[email protected]"))Copy the code

The message content can contain the body and/or HTML:

msg.body = "testing"
msg.html = "<b>testing</b>"Copy the code

Finally, use the Flask application Mail instance to send Mail:

mail.send(msg)Copy the code

A lot of mail

Typically, one or two emails are sent for each request in a Web application. In certain scenarios, tens or hundreds of messages may be sent, but this is done by off-line tasks or script execution.

The code for sending mail in this case is slightly different:

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

        conn.send(msg)Copy the code

The connection to the E-mail server remains active until all messages have been sent and then is closed (disconnected).

Some mail servers limit the number of messages that can be sent in a connection. You can set the maximum number of emails that can be sent before reconnecting by configuring MAIL_MAX_EMAILS.

The attachment

Attaching an attachment to a message is also very simple:

with app.open_resource("image.png") as fp:
    msg.attach("image.png"."image/png", fp.read())Copy the code

If MAIL_ASCII_ATTACHMENTS is set to True, the file names are converted to ASCII. The MAIL_ASCII_ATTACHMENTS configuration is useful when the file name is encoded in UTF-8 and mail forwarding modifies the mail Content and obfuscates the Content-Disposition description. The basic way to convert to ASCII is to remove non-ASCII characters. Any Unicode character can be decomposed into one or more ASCII characters by NFKD.

A complete example

Assume that you have enabled the STMP service of qq mailbox and configured the flask and flask-mail environment.

# -*- coding: utf-8 -*-
from flask import Flask, request
from flask_script import Manager, Shell
from flask_mail import Mail, Message
from threading import Thread


app = Flask(__name__)
app.config['MAIL_DEBUG'] = True             Enable debug to view information easily
app.config['MAIL_SUPPRESS_SEND'] = False    # send mail, if True, do not send mail
app.config['MAIL_SERVER'] = 'smtp.qq.com'   # email server
app.config['MAIL_PORT'] = 465               # port
app.config['MAIL_USE_SSL'] = True           # Important, THE QQ mailbox needs to use SSL
app.config['MAIL_USE_TLS'] = False          No need to use TLS
app.config['MAIL_USERNAME'] = '[email protected]'  # fill in the email
app.config['MAIL_PASSWORD'] = 'xxxxxx'      Fill in the authorization code
app.config['MAIL_DEFAULT_SENDER'] = '[email protected]'  # fill the mailbox, default sender
manager = Manager(app)
mail = Mail(app)


Send email asynchronously
def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)


@app.route('/')
def index(a):
    msg = Message(subject='Hello World',
                  sender="[email protected]".If you want to use the default sender, leave this field blank
                  recipients=['[email protected]'.'[email protected]'])
    Email content will be presented in both text and HTML format, which format you will see depending on your email client.
    msg.body = 'sended by flask-email'
    msg.html = ' Test Flask send mail '
    thread = Thread(target=send_async_email, args=[app, msg])
    thread.start()
    return '

Message sent successfully

'
if __name__ == '__main__': manager.run() Copy the code

Env “and use python-envcfg to read the configuration, e.g. App.config. from_object(‘ envcfg.raw ‘).


Reference: Flask – Email manual