Use Flask-Mail to develop Mail API tutorials

Source: Internet
Author: User
Tags imap

I have also written python smtplib to send emails. It is an application written based on the smtpmlib module. Here I want to use flask to write a simple API. The specific application scenario is, in a LAN environment, only one host can send emails outside the Internet. Other hosts cannot access the Internet. This host starts a flask API mail sending service. When other hosts need to send alarm emails, they can call this host's mail service to send outgoing alarm messages. The implementation of this function is divided into two parts. The first part describes the fask-mail module, and the second part describes how to implement this function.

1. Introduction to the flask-mail module

At the beginning, I also want to refer to the earlier smtplib and call the program via flask. However, the mail extensions of flask include the ready-made modules flask-mail and flask. ext. mail and flask-sendmail. Use flask-mail here. Flask-Mail provides a simple interface that allows us to conveniently send emails using the SMTP protocol in the Flask application.

II. Installation and Use of the flask-mail module

1. Installation

Pip install Flask-Mail or
Easy_install Flask-Mail
Check the source code of this module and find that it is implemented by calling the smtplib module.

2. Configuration

Flask-Mail uses the Flask standard configuration API for configuration. The following are all configuration options:

MAIL_SERVER: The default value is 127. 0.0.1'
MAIL_PORT: The default value is 25.
MAIL_USE_TLS: The default value is False.
MAIL_USE_SSL: The default value is False.
MAIL_DEBUG: The default value is app. debug.
MAIL_USERNAME: The default value is None.
MAIL_PASSWORD: The default value is None.
MAIL_DEFAULT_SENDER: The default value is None.
MAIL_MAX_EMAILS: The default value is None.
MAIL_SUPPRESS_SEND: The default value is app. testing.
MAIL_ASCII_ATTACHMENTS: The default value is False.
For specific parameters, see the source code.

3. Initialization

This is also described in the official document. There are two methods.

Method 1:

Use the configuration items of the application passed in to the Mail instance to send the Mail:

From flask import Flask
From flask_mail import Mail
App = Flask (_ name __)
Mail = Mail (app)
Method 2:

Use the configuration items in current_app of Flask to send emails. If we have multiple applications with different configurations, this method is more convenient:

Mail = Mail ()
App = Flask (_ name __)
Mail. init_app (app)
3. Use flask-mail to send emails

Sending details

Before sending the Message, we need to build a Message object, as shown below:

From flask_mail import Message
Msg = Message ("Hello Flask", sender = "itybku@gmail.com", recipients = ["itybku@163.com"])
You can also specify multiple recipients at the same time:

Msg. recipients = ["itybku@gmail.com", "itybku@163.com"]
Msg. add_recipient ("itybku@126.com ")
If the MAIL_DEFAULT_SENDER field is configured, the sender is no longer set. In this case, the sender specified in MAIL_DEFAULT_SENDER is used, as shown in the following code:

Msg = Message ("Hello Flask", recipients = ["itybku@live.com"])
If you want to display a name (string) in the receiving list, you can specify it using a binary ancestor:

Msg = Message ("Hello", sender = ("itybku", "itybku@live.com "))
At the same time, we can also specify the following two fields:

Msg. body = "this is body string"
Msg.html = "Finally, send:

Mail. send (msg)
After sending the email, the link to the email server is closed.

Send a large number of emails

If we send a large number of emails at a time, we can send them in the following way:

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)
The connection to the email server will remain until all emails have been sent. Note that when sending a large number of messages, you can also set the MAIL_MAX_EMAILS variable.

Some mail servers set a limit on the number of emails sent in a single connection.
You can set the max amount of emails to send before reconnecting by specifying theMAIL_MAX_EMAILS setting.
Add Attachment

With app. open_resource ("image.png") as fp:
Msg. attach ("image.png", "image/png", fp. read ())
Example of not using SSL

# Coding: UTF-8
From flask import Flask
From flask_mail import Mail, Message
App = Flask (_ name __)
App. config ['mail _ server'] = 'smtp .163.com'
App. config ['mail _ port'] = 25
App. config ['mail _ USE_SSL '] = False
App. config ['mail _ username'] = 'sender @ 163.com'
App. config ['mail _ password'] = 'password'
App. config ['mail _ DEFAULT_SENDER '] = 'sender @ 163.com'
Mail = Mail (app)
@ App. route ("/")
Def index ():
Msg = Message ('This is a test Message head', recipients = ['itybku @ 139.com '])
Msg. body = "This is the email body"
Msg.html = 'Hello api'
Mail. send (msg)
Return "Sent"
If _ name _ = "_ main __":
App. run (host = "0.0.0.0", port = 5000, debug = True)
# App. run ()
           
SSL example (with attachment)

#! /Usr/bin/env python
# Coding: UTF-8
From flask import Flask
From flask_mail import Mail, Message
App = Flask (_ name __)
App. config ['mail _ server'] = 'smtp .qq.com'
App. config ['mail _ port'] = 465
App. config ['mail _ USE_SSL '] = True
App. config ['mail _ username'] = 'sender @ qq.com'
App. config ['mail _ password'] = '********'
App. config ['mail _ DEFAULT_SENDER '] = 'sender @ qq.com'
Mail = Mail (app)
@ App. route ('/mail ')
Def welcome ():
Msg = Message ('This is a test Message head', recipients = ['itybku @ 100'])
Msg. body = 'This is a test email bodyer'
Msg.html = 'this is a test email htmler'
Image = 'image _. Road to O & M jpg'
With app. open_resource (image) as fp:
Msg. attach (image, 'image/jpg ', fp. read ())
Mail. send (msg)
Return 'Hello world! '
If _ name _ = '_ main __':
App. run (debug = tuple)
Note: You need to configure the SMTP, IMAP, and other protocols in QQ mail. Choose QQ Mail> Settings> POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV Service> to generate an authorization code.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.