Django 中的各种邮件发送
修改setting.py 加入邮箱配置
1 EMAIL_USE_SSL = True #是否使用加密 2 3 EMAIL_HOST = 'smtp.qq.com' #smtp服务器, 如果是 163 改成 smtp.163.com 4 5 EMAIL_PORT = 465 #465对应QQ邮箱SMPT的端口,不能改 6 7 EMAIL_HOST_USER = "1316843429@qq.com" 8 9 EMAIL_HOST_PASSWORD = "bbrpcgvidvwficda" #授权码 10 11 DEFAULT_FROM_EMAIL = EMAIL_HOST_USER #默认邮件发送人
普通邮件发送
1 from django.core.mail import send_mail 2 from django.conf import settings 3 4 def test_email(req): 5 title = '来自Django的问候' #邮件标题 6 msg = 'It is our choices that show what we truly are, far more than our abilities. ——J·K·罗琳 ' #邮件内容 7 receivers = [ 8 'wusir666666@163.com', 9 '1933972786@qq.com' 10 ] #收件人列表 11 email_from = settings.DEFAULT_FROM_EMAIL #发件人 12 send_mail(title,msg,email_from,receivers) #邮件发送 13 return HttpResponse('ok')
模板邮件发送
views函数:
1 from django.template import loader 2 from django.core.mail import send_mail 3 4 def send_html(req): 5 tilte = '名著' # 邮件标题 6 template = loader.get_template('email_template.html') #模板加载 7 template_str = template.render({'title':'名著','url':'https://www.juzimi.com/ju/49719'}) #模板渲染 8 receivers = [ 9 'wusir666666@163.com', 10 '1933972786@qq.com' 11 ] #收件人列表 12 email_from = settings.DEFAULT_FROM_EMAIL #发件人 13 send_mail(tilte,'',email_from,receivers,html_message=template_str) #邮件发送 14 return HttpResponse('已发送')
模板函数:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>{{ title }}</title> 6 </head> 7 <body> 8 <h3>你以为,我可以很迅速的恢复过来,有些自私的以为。<br> 9 从阴雨走到艳阳,我路过泥泞、路过风。<br> 10 一路走来,你不曾懂我,我亦不曾怪你。<br> 11 我不是为了显示自己的大度,<br> 12 也不是为了体现自己的大方。<br> 13 只想让你知道,感情不在,责备也不存在。</h3> 14 <a href="{{ url }}">{{ url }}</a> 15 <h1 style="color: red">名著摘抄</h1> 16 </body> 17 </html>
邮件加附件发送
1 from django.core.mail import EmailMessage 2 from django.conf import settings 3 4 def file_email(req): 5 title = '悲惨世界' #邮件标题 6 msg = ' 他安息了。尽管命运多舛,他仍偷生。失去了他的天使他就丧生;事情是自然而然地发生,就如同夜幕降临,白日西沉。' # 邮件内容 7 receivers = [ 8 'wusir666666@163.com', 9 '1933972786@qq.com' 10 ] #收件人列表 11 email_from = settings.DEFAULT_FROM_EMAIL #发件人 12 message = EmailMessage(title,msg,email_from,receivers) 13 file_path = os.path.join(settings.STATICFILES_DIRS[0],'10.jpg') 14 # 加载附件路径,attach_file多个就可以添加多个附件 15 message.attach_file(file_path,mimetype='image/jpg') #将邮件内容和附件打包到message 16 message.send() #发送打包好的邮件 17 return HttpResponse('邮件已发送')
多封邮件发送
1 from django.core.mail import send_mass_mail 2 from django.conf import settings 3 4 def send_many_msg(req): 5 receivers = [ 6 'wusir666666@163.com', 7 '1933972786@qq.com' 8 ] #收件人列表 9 email_from = settings.DEFAULT_FROM_EMAIL #发件人 10 msg1 = ('标题','得之我幸,失之我命,如此而已。 ——徐志摩',email_from,receivers) 11 msg2 = ('还是标题','最是那一低头的温柔,恰似一朵水莲花不胜凉风的娇羞 。——徐志摩',email_from,receivers) #打包好的两封邮件 12 send_mass_mail((msg1,msg2)) #发送邮件 13 return HttpResponse('OKK')
Fake it,till you make it