利用django发送邮件

需要把qq邮件的POP3/SMTP服务打开 位置 设置–>账户
利用django发送邮件settings

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.qq.com'
EMAIL_PORT = 25
#发送邮件的邮箱
EMAIL_HOST_USER = '发送到哪个qq的邮箱'
#在邮箱中设置的客户端授权密码
EMAIL_HOST_PASSWORD = '自己的授权码'
#收件人看到的发件人
EMAIL_FROM = '海马生鲜<2569792062@qq.com>'
import djcelery
djcelery.setup_loader()
BROKER_URL = 'redis://127.0.0.1:6379/9'
CELERY_IMPORTS = ('celery_tasks.tasks')

发送邮件一般都是和注册信息绑定在一块
views

class RegisterView(View):
    def get(self,request):
        return render(request,'register.html')
    def post(self,request):
        # 获取前端发送的账号、密码、邮件
        username = request.POST.get('user_name')
        password = request.POST.get("pwd")
        email = request.POST.get("email")
        allow = request.POST.get("allow")
        # 判断是否都存在数据
        if not all([username, password, email]):
            return render(request, 'register.html', {"error": "数据不完整"})
        # 判断邮件的格式是否正确
        if not re.match(r"^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$", email):
            return render(request, "register.html", {"error": "邮箱格式不正确"})
        # 判断是否画上勾
        if allow != "on":
            return render(request, "register.html", {"error": "请勾选同意"})
        try:
            # 判断前端发送过来的账号匹配是否存在
            User.objects.get(username=username)
            return render(request,'register.html',{'error':"用户已存在"})
        except User.DoesNotExist:
            # 不存在将存进数据库
            user = User.objects.create_user(username=username, password=password, email=email)
            # 0表示账号未激活
            user.is_active =0
            user.save()
            # 加密用户id,生成激活的token
            serializer = Serializer(settings.SECRET_KEY,3600)
            info = {"confirm":user.id}
            token = serializer.dumps(info).decode()
            # 调用tasks中的send_active_email函数并且发送邮件
            send_active_email.delay(email,username,token)
            return redirect(reverse('Users:login'))

邮件激活

class ActiveView(View):
    def get(self,request,token):
        # 加密用户身份信息,生成激活token
        #Serializer的第一个参数是用户加密的密钥,
        # 第二个参数是生成的加密数据的有效时间秒(s)
        serializer = Serializer(settings.SECRET_KEY, 3600)
        try:
            info = serializer.loads(token)
            # 获取id
            user_id = info['confirm']
            # 根据id获取用户对象
            user = User.objects.get(id=user_id)
            # 将值改为1说明已经激活
            user.is_active = 1
            user.save()
            return redirect(reverse('Users:login'))
        except SignatureExpired as e:
            return HttpResponse("激活链接已过期")

创建一个名叫celery_tasks的文件夹,里面存在一个tasks.py文件

from celery import Celery
from Hippocampal import settings
from django.core.mail import send_mail
import os
import django
import time
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Hippocampal.settings")
django.setup()

app = Celery("celery_tasks.tasks", broker="redis://127.0.0.1:6379/4")

@app.task
def send_active_email(email,username,token):
    subject = "海马生鲜欢迎你"
    message = ''
    sender = settings.EMAIL_FROM
    receiver = [email]
    html_message = """
             <h1>%s  恭喜您成为海马生鲜注册会员</h1><br/><h3>请您在1小时内点击以下链接进行账户激活</h3>
             <a href="http://127.0.0.1:8000/registerace/%s">http://127.0.0.1:8000/regtive/%s</a>
             """ % (username, token, token)
    send_mail(subject, message, sender, receiver, html_message=html_message)

    time.sleep(15)

urls

re_path('active/(?P<token>.*)$',views.ActiveView.as_view(),name='active'),

要发送邮件需要打开redis
使用celery -A celery_tasks.tasks worker -l info就可以发送邮件了

利用django发送邮件利用django发送邮件 喜欢双眼皮h 发布了12 篇原创文章 · 获赞 0 · 访问量 255 私信 关注
上一篇:spring自带的定时任务功能@EnableScheduling


下一篇:用Java控制内部队列