table of Contents
First, the experimental environment
Python3.7 + Django2.1.3
Second, obtain authorization code QQ-mail
1. What is an authorization code?
QQ mailbox authorization code is introduced for specific password to log a third-party client.
Login applies to the following services: POP3 / IMAP / SMTP / Exchange / CardDAV / CalDAV service.
Reminder: In order to secure your account, change the password QQ password and independence will trigger the authorization code expires, you need to obtain a new authorization code to log on.
2, how to obtain an authorization code?
Action: Set ---> account, in accordance with the following process operations.
(1) Click on "authorization code"
(2) verify the secret security
(3) obtain authorization code
Three, Django configured
In the following code setting.py
# Host for sending email.
EMAIL_HOST = 'smtp.qq.com' # 发送方的smtp服务器地址
# Port for sending email.
EMAIL_PORT = 587 # smtp服务端口
# Optional SMTP authentication information for EMAIL_HOST.
EMAIL_HOST_USER = 'you [email protected]' # 发送方 邮箱地址
EMAIL_HOST_PASSWORD = 'uzlbagwxizkfcfdf' # 获得的 授权码
EMAIL_USE_TLS = True # 必须为True
EMAIL_USE_SSL = False
EMAIL_SSL_CERTFILE = None
EMAIL_SSL_KEYFILE = None
EMAIL_TIMEOUT = None
# Default email address to use for various automated correspondence from
# the site managers.
DEFAULT_FROM_EMAIL = 'you [email protected]' # 和 EMAIL_HOST_USER 相同
- note:
- Do not add authorization code reported SMTPAuthenticationError error,
Text messages
send_email.py code is as follows:
import os
from django.core.mail import send_mail
os.environ['DJANGO_SETTINGS_MODULE'] = 'suosuo.settings' # 必须添加 , 依赖于 Django
if __name__ == '__main__':
res = send_mail(
'来自www.liujiangblog.com的测试邮件',
'欢迎访问www.cnblogs.com/shiwei1930,这里是SUOSUO博客站点,本站专注于Python、Django技术的分享!',
'you [email protected]',
['target [email protected]'],
)
print('res=', res) # 成功 返回 1
# 对于send_mail方法,
# 第一个参数是邮件主题subject;
# 第二个参数是邮件具体内容;
# 第三个参数是邮件发送方,
# 第四个参数是接受方的邮件地址列表, 需要和你settings中的一致;
HTML Mail
send_email.py code is as follows:
import os
from django.core.mail import EmailMultiAlternatives
os.environ['DJANGO_SETTINGS_MODULE'] = 'suosuo.settings'
if __name__ == '__main__':
subject = '来自www.cnblogs.com/shiwei1930的测试邮件'
from_email= 'you [email protected]'
to = ['target [email protected]']
text_content = '欢迎访问www.cnblogs.com/shiwei1930,这里是SUOSUO站点,专注于Python和Django技术的分享!'
html_content = '<p>欢迎访问<a href="http://www.cnblogs.com/shiwei1930" target=blank>www.cnblogs.com/shiwei1930</a>,这里是SUOSUO站点,本站专注于Python、Django的分享!</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, to)
msg.attach_alternative(html_content, "text/html")
msg.send()
# 其中的text_content是用于当HTML内容无效时的替代txt文本。