基于qq的邮件发送服务:
django.settings设置:
EMAIL_HOST_USER = 'xxxxx@qq.com' # 在这里填入您的QQ邮箱账号 EMAIL_PORT = 465 EMAIL_HOST_PASSWORD = 'xxxxxxx' # 请在这里填上您自己邮箱的授权码 EMAIL_HOST = 'smtp.qq.com' # 如果是 163 改成 smtp.163.com DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_USE_SSL = True
django.views:
from django.core.mail import EmailMultiAlternatives
from pen_web.settings import dev
class EmailPwd(APIView): def get(self, request): email_ = request.query_params.get("email") logger.info(email_) email_tb = Userinfo.objects.filter(email=email_) if not email_tb: return HttpResponeseJson(code=400, message='该邮箱并未注册,请直接注册登录。') # 从a-zA-Z0-9生成指定数量的随机字符 ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 6)) msg_html = '''<!DOCTYPE html> <html> <meta charset="UTF-8"> <head> <title>密码找回</title> </head> <body> <div>尊敬的用户您好:</div> <p>要完成密码找回我们只需要确保这是您的电子邮件地址:</p> <span style="color:red">{email}</span>, <p>或者可能会要求你输入安全代码号:</p> <span style="color:blue;font-size:20px;">{code}</span> <p>请在您邮箱申请密码找回页输入:安全代码号和新密码。</p> </body> </html> '''.format(email=email_, code=ran_str) try:
#把文字样式单独放入html文件中,需要注意以下注释部分内容。 # context = { # 'email': str(email_), # 'code': str(ran_str), # # } # 发送的html模板的名称 # email_template_name = 'email_template.html'#如果是html文件的引入,html所在变量位置需要{{}}双大括号来包裹变量:<span style="color:red">{{email}}</span>, # t = loader.get_template(email_template_name) # html_content = t.render(context) html_content = msg_html msg = EmailMultiAlternatives("密码找回", html_content, dev.EMAIL_HOST_USER, [email_]) msg.attach_alternative(html_content, "text/html") msg.send() except Exception as e: return HttpResponeseJson(code=400, message='邮件发送失败{e}'.format(e=e)) else: return HttpResponeseJson(message='邮件发送成功,请登录邮箱获取安全代码号。')
注意:
1,HttpResponeseJson是个人重新封装后的固定返回格式,请自行修改。
2,本实例也是基于django rest framework上书写。