在Django中发送电子邮件

时间:2018-12-21 13:56:51

标签: django email

我想在用户注册时向其发送电子邮件。 我已经编写了用于在我的form.py

中发送电子邮件的代码

下面是代码段:

forms.py

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.conf import settings

#User registration form
class UserRegisterForm(UserCreationForm):
     email = forms.EmailField()  #default is required=True

    class Meta:
        model = User #user model will be affected

        fields = ['first_name','username','email','password1','password2']

    def send_email(self):
        name = self.cleaned_data.get('first_name')
        username = self.cleaned_data.get('username')
        to_email = self.cleaned_data.get('email')
        password = self.cleaned_data.get('password')
        subject = 'Login details for Django_app'
        from_email = settings.EMAIL_HOST_USER
        context = {
            'name': name,
            'username': username,
            'email': to_email,
            'password': password,
        }

        plaintext = get_template('register_email.txt')
        htmly = get_template('register_email.html')
        text_content = plaintext.render(context)
        html_content = htmly.render(context)

        message = EmailMultiAlternatives(
            subject=subject,
            body=text_content,
            from_email=from_email,
            to=[to_email]
        )
        message.attach_alternative(html_content, "text/html")
        message.send()

当我注册用户的电子邮件没有发送时,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

在我看来,您的send_email()方法从未被调用!

您最终可以重载模型保存方法并在内部调用方法:

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()  #default is required=True

    class Meta:
        model = User #user model will be affected
        fields = ['first_name','username','email','password1','password2'] 

    # bla bla

    def save(self, commit=True):
        instance = super().save(commit)
        self.send_email()  # there you send the email when then model is saved in db
        return instance

另一种选择是使用signals