django发送邮件

1、开启邮箱的SMTP服务:登录qq邮箱->设置->账户->打开POP3/SMTP

 

2、在settings.py最后加上:

1 #settings
2 
3 EMAIL_USE_SSL = True
4 EMAIL_HOST = 'smtp.qq.com'  # 如果是 163 改成 smtp.163.com
5 EMAIL_PORT = 465
6 EMAIL_HOST_USER = 'xxx@qq.com' # 帐号
7 EMAIL_HOST_PASSWORD = 'password'  # SMTP服务密码
8 DEFAULT_FROM_EMAIL = EMAIL_HOST_USER 

 

3、编辑views

 1 #一次发送一个
 2 from django.core.mail import send_mail
 3  
 4 send_mail('Subject here', 'Here is the message.', 'from@example.com',
 5     ['to@example.com'], fail_silently=False)
 6  
 7 #一次发送多个
 8 from django.core.mail import send_mass_mail
 9  
10 message1 = ('Subject here', 'Here is the message', 'from@example.com', ['first@example.com', 'other@example.com'])
11 message2 = ('Another Subject', 'Here is another message', 'from@example.com', ['second@test.com'])
12  
13 send_mass_mail((message1, message2), fail_silently=False)   
14 
15 #备注:send_mail 每次发邮件都会建立一个连接,发多封邮件时建立多个连接。而 send_mass_mail 是建立单个连接发送多封邮件,所以一次性发送多封邮件时 send_mass_mail 要优于 send_mail。

 

参考:https://code.ziqiangxuetang.com/django/django-send-email.html

https://www.jianshu.com/p/334f0b32f7a1

 

posted @ 2019-11-29 14:28  一只小羊  阅读(213)  评论(0编辑  收藏  举报