Django初体验(三):邮件配置[转]

本篇博客来自于:http://www.cnblogs.com/BeginMan/p/3443158.html 

Django发送邮件官方中文文档

总结如下:
1、首先这份文档看三两遍是不行的,很多东西再看一遍就通顺了。
2、send_mail()send_mass_mail()都是对EmailMessage类使用方式的一个轻度封装,所以要关注底层的EmailMessage
3、异常处理防止邮件头注入。
4、一定要弄懂Email backends 邮件发送后端
5、多线程的邮件发送。
个人简单配置如下:
首先是settings.py文件

复制代码
#settings.py

#邮件配置
EMAIL_HOST = 'smtp.gmail.com'                   #SMTP地址
EMAIL_PORT = 25                                 #SMTP端口
EMAIL_HOST_USER = '[email protected]'       #我自己的邮箱
EMAIL_HOST_PASSWORD = '******'                  #我的邮箱密码
EMAIL_SUBJECT_PREFIX = u'[CoorCar网]'            #为邮件Subject-line前缀,默认是'[django]'
EMAIL_USE_TLS = True                             #与SMTP服务器通信时,是否启动TLS链接(安全链接)。默认是false
#管理员站点
SERVER_EMAIL = '[email protected]'            #The email address that error messages come from, such as those sent to ADMINS and MANAGERS.
复制代码

 

发送邮件如下:

复制代码
def setEmail(request):
    
    if request.method == "POST":
#        方式一:
#         send_mail('subject', 'this is the message of email', '[email protected]', ['[email protected]','[email protected]'], fail_silently=True)

#        方式二:
#         message1 = ('subject1','this is the message of email1','[email protected]',['[email protected]','[email protected]'])
#         message2 = ('subject2','this is the message of email2','[email protected]',['[email protected]','[email protected]'])
#         send_mass_mail((message1,message2), fail_silently=False)

#        方式三:防止邮件头注入
#         try:
#             send_mail(subject, message, from_email, recipient_list, fail_silently, auth_user, auth_password, connection)
#         except BadHeaderError:
#             return HttpResponse('Invaild header fount.')

#        方式四:EmailMessage()
        #首先实例化一个EmailMessage()对象
#         em = EmailMessage('subject','body','[email protected]',['[email protected]'],['[email protected]'],header={'Reply-to':'[email protected]'})
        #调用相应的方法
        
#         方式五:发送多用途邮件
        subject,form_email,to = 'hello','[email protected]','[email protected]'
        text_content = 'This is an important message'
        html_content = u'<b>激活链接:</b><a href="http://www.baidu.com">http:www.baidu.com</a>'
        msg = EmailMultiAlternatives(subject,text_content,form_email,[to])
        msg.attach_alternative(html_content, 'text/html')
        msg.send()
        
#       发送邮件成功了给管理员发送一个反馈
#         mail_admins(u'用户注册反馈', u'当前XX用户注册了该网站', fail_silently=True)
        return HttpResponse(u'发送邮件成功')
    return render_to_response('common/test.html')

你可能感兴趣的:(Django初体验(三):邮件配置[转])