「Django」Django内置email发送邮件

Django内置email发送邮件

1、首先在settings.py文件设置相关参数

STATIC_URL = '/static/'
# 设置邮件域名 
EMAIL_HOST = 'smtp.163.com'
# 设置端口号,为数字
EMAIL_PORT = 25
#设置发件人邮箱
EMAIL_HOST_USER = 'xxxxx@163.com'
# 设置发件人 授权码
EMAIL_HOST_PASSWORD = '自己的授权码'
# 设置是否启用安全链接
EMAIL_USER_TLS = True

# 以上这个配置信息,Django会自动读取,
# 使用账号以及授权码进行登录,
# 如果登录成功,可以发送邮件

2、回到views.py 文件,加入以下代码

# 引入发送邮件的模块
from django.core.mail import send_mail, send_mass_mail, EmailMultiAlternatives
from django.conf import settings

send_mail('关于中秋节放假通知',
        '中秋节放三天假',
        'qiqi1931@163.com',
        ['qiqi1931@163.com']
        fail_silently = False)
        # 值1:邮件标题   值2:邮件主人  值3:发件人  值4:收件人  值5:如果失败,是否抛出错误 
if res == 1:
    return HttpResponse('邮件发送成功')
else:
    return HttpResponse('邮件发送失败')

3、多封给多个人进行发送

message1 = ('这个周日你有空吗',
         '孔子东游见两小儿便日',
         'qiqi1931@163.com',
         ['891811395@qq.com', '819614513@qq.com'])

message2 = ('这个周 日你有空吗?',
        '孔子东游,见两小儿,便日',
         'qiqi1931@163.com',
         ['891811395@qq.com', '1311173658@qq.com'])
res = send_mass_email((message1, message2))
if res == 2:
   return HttpResponse('多封邮件发送成功')
else:
   return HttpResponse('多封邮件发送失败')

4、进阶使用,多线程异步发送

  • utils添加sendEmail.py文件
import threading
from django.core.mail import send_mail
from django.conf import settings


class SendMail(threading.Thread):
    def __init__(self,subject,text,email,fail_silently=False):
        self.subject = subject
        self.text = text
        self.email = email
        self.fail_silently = fail_silently
        threading.Thread.__init__(self)

    def run(self):
        send_mail(
            self.subject,
            self.text,
            settings.EMAIL_HOST_USER,
            [self.email],
            fail_silently=self.fail_silently
        )
  • 调用方法
send_mail = SendMail(subject,text,email)
send_mail.start()
posted @ 2019-05-29 18:11  子谦0618  阅读(1980)  评论(0编辑  收藏  举报