任何人都可以建议如何使用send_mail发送电子邮件?它不起作用

问题描述 投票:1回答:1

用户注册时,is_active默认为False。我希望用户在管理员激活用户时收到电子邮件通知。但是send_mail没有发送电子邮件。

我在views.py中创建了一个函数:

def send_mail(request):
    if user.is_active == True:
        send_mail(request, subject='subject',
          message='message',
          from_email='[email protected]',
          recipient_list=['[email protected]'],
          fail_silently=False)

我也在settings.py中记下了这些东西:

EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'ualmaz'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 25
EMAIL_USE_TLS = False

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_FILE_PATH = os.path.join(BASE_DIR, 'apps', 'emails')

这是我的views.py:

from django.shortcuts import render, redirect
from django.contrib import messages
from django.core.mail import send_mail
from django.urls import reverse_lazy
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import CreateView, DetailView, ListView, UpdateView, DeleteView
from .forms import UserCreationModelForm, UserUpdateForm, ProfileUpdateForm
from .models import User, Post, Profile

class UserRegistrationView(CreateView):
    form_class = UserCreationModelForm
    user = User
    success_url = reverse_lazy('login')
    template_name = 'users/registration.html'

def send_mail(request):
    user = User
    if user.is_active == True:
        send_mail(request, subject='subject',
          message='message',
          from_email='[email protected]',
          recipient_list=['[email protected]'],
          fail_silently=False)

这是models.py中的用户模型:

class User(AbstractUser):
    first_name = models.CharField(verbose_name="First name", max_length=255)
    last_name = models.CharField(verbose_name="Last name", max_length=255)
    country = models.CharField(verbose_name="Country name", max_length=255)
    city = models.CharField(verbose_name="City name", max_length=255)
    email = models.EmailField(verbose_name="Email", max_length=255)
    access_challenge = models.BooleanField(default=False)
    is_active = models.BooleanField(default=False)

    def __str__(self):
        return self.username

有任何想法吗?

python django
1个回答
0
投票

这是怎么解决的。

from django.dispatch import receiver
from django.db.models.signals import pre_save, post_save
from django.conf import settings
from django.core.mail import send_mail


#signal used for is_active=False to is_active=True
@receiver(pre_save, sender=User, dispatch_uid='active')
def active(sender, instance, **kwargs):
    try:
        if instance.is_active and User.objects.filter(pk=instance.pk, is_active=False).exists():
            subject = 'Your account is activated'
            mesagge = '%s your account is now active' %(instance.first_name)
            from_email = settings.EMAIL_HOST_USER
            send_mail(subject, mesagge, from_email, [instance.email], fail_silently=False)
    except:
        print("Something went wrong, please try again.")


#signal to send an email to the admin when a user creates a new account
@receiver(post_save, sender=User, dispatch_uid='register')
def register(sender, instance, **kwargs):
    try:
        if kwargs.get('created', False):
            subject = "Verificatión of the %s 's account" %(instance.username)
            mesagge = '%s, %s just registered in locator' %(instance.first_name, instance.last_name)
            from_email = settings.EMAIL_HOST_USER
            send_mail(subject, mesagge, from_email, [from_email], fail_silently=False)
    except:
        print("Something went wrong, please try again.")
© www.soinside.com 2019 - 2024. All rights reserved.