2

我有一个使用 Djoser 进行身份验证的 DRF 项目。计划是覆盖 Djoser 的默认激活电子邮件并发送一些 HTML 模板电子邮件。这是我所拥有的:

# settings.py

DJOSER = {
    "SEND_ACTIVATION_EMAIL": True,
    "ACTIVATION_URL": "activate/{uid}/{token}",
    "EMAIL": {"activation": "base.emails.ActivationEmail"},
}
# base/emails

from django.contrib.auth.tokens import default_token_generator
from djoser import email, utils
from djoser.conf import settings


class ActivationEmail(email.ActivationEmail):
    template_name = "emails/activation.html"

    def get_context_data(self):
        # ActivationEmail can be deleted
        context = super().get_context_data()

        user = context.get("user")
        context["first_name"] = user.first_name
        context["uid"] = utils.encode_uid(user.pk)
        context["token"] = default_token_generator.make_token(user)
        context["url"] = settings.ACTIVATION_URL.format(**context)
        return context

# templates/emails/activation.html

{% extends "emails/base.html" %}

{% load static %}

{% block subject %}Account Activation on Dummy{% endblock %}

{% block heading %}
    Account Activation
{% endblock %}

{% block content %}
    You're receiving this email because you need to finish activation process.
    Please click on the button below to activate your account:

    <br><br><br>
    <a
        href="{{ url }}"
        target="_blank"
        style="
            text-decoration: none;
            font-family: lato, 'helvetica neue', helvetica, arial, sans-serif;
            font-size: 20px;
            color: #fff;
            background-color: #0b913a;
            padding: 10px 25px;
            border-radius: 5px;
        "
        >Activate</a
    >
    <br><br><br>

    Best Regards,<br>
    The DUMMY Team

    <br><br>
    <p
        style="
            margin: 0;
            -webkit-text-size-adjust: none;
            -ms-text-size-adjust: none;
            mso-line-height-rule: exactly;
            font-size: 14px;
            font-family: lato, 'helvetica neue', helvetica, arial, sans-serif;
            line-height: 21px;
            color: #666666;
        "
    >
        If you did not make this request, reply to this email or write to info@dummy.com so we can 
        look into a possible attempt to impersonate you.
    </p>
{% endblock %}

一切似乎都正确,但电子邮件没有发送。我检查收件箱,什么也没看到。但是,当我删除指向自定义电子邮件的删除 EMAIL 设置时,它会发送默认的 Djoser 激活电子邮件。怎么了?

4

1 回答 1

0

我只是将它与我​​的项目中使用 Djoser 的自定义激活电子邮件进行了比较,您的配置看起来非常相似。

ActivationEmail里面有个方法send。您可能想要覆盖它并添加一些日志。也许这会有所帮助。

    def send(self, to, *args, **kwargs):
        logger.info(f"Sending activation mail to {to}")
        try:
            super().send(to, *args, **kwargs)
        except:
            logger.exception(f"Couldn't send mail to {to}")
            raise
        logger.info(f"Activation mail sent successfully to {to}")

无论如何,只是写一个测试。在您的测试中,您可以使用以下方式检查电子邮件是否已发送

self.assertEqual(len(mail.outbox), 1)

从哪里来mail

from django.core import mail

于 2021-05-21T08:21:31.287 回答