Newletter Views not sending Emails after being saved with no error showing

Submitted 4 years, 3 months ago
Ticket #28
Views 286
Language/Framework Django
Priority Low
Status Closed

Hi Teckiys,

I have created a newsletter app to send emails to subscribers. After adding a new newsletter and setting it to be equal to published it should send the email, but instead, the newsletter is saved with no emails sent.

I am sure that the email setting is correct as I am receiving an email after a successful subscription for testing.

Here is the complete views.py

def newsletter_signup(request):
    form = NewsletterUserSignupForm(request.POST or None)

    if form.is_valid():
        instance = form.save(commit=False)
        if NewsletterUser.objects.filter(email=instance.email).exists():
            messages.warning(
                request, 'Your email is already exists in our database')
        else:
            instance.save()
            messages.success(
                request, 'Your email has been added in our database')
            subject = "Thank you for Joining our Newsletter"
            from_email = settings.EMAIL_HOST_USER
            to_email = [instance.email]
            with open(settings.BASE_DIR + "/templates/newsletter_signup_email.txt") as f:
                signup_message = f.read()
            message = EmailMultiAlternatives(
                subject=subject, body=signup_message, from_email=from_email, to=to_email)
            html_template = get_template(
                "newsletter_signup_email.html").render()
            message.attach_alternative(html_template, "text/html")
            message.send()

    context = {'form': form}
    template = "newsletters_signup.html"
    return render(request, template, context)


def newsletter_unsubscribe(request):
    form = NewsletterUserSignupForm(request.POST or None)
    if form.is_valid():
        instance = form.save(commit=False)
        if NewsletterUser.objects.filter(email=instance.email).exists():
            NewsletterUser.objects.filter(email=instance.email).delete()
            messages.success(
                request, 'Your email has been removed from our database')
            subject = "You have been removed from our newsletter"
            from_email = settings.EMAIL_HOST_USER
            to_email = [instance.email]
            with open(settings.BASE_DIR + "/templates/newsletter_unsubscribe_email.txt") as f:
                signup_message = f.read()
            message = EmailMultiAlternatives(
                subject=subject, body=signup_message, from_email=from_email, to=to_email)
            html_template = get_template(
                "newsletter_unsubscribe_email.html").render()
            message.attach_alternative(html_template, "text/html")
            message.send()
        else:
            messages.warning(
                request, 'Your email is not in our database')
    context = {'form': form}
    template = "newsletter_unsubscribe.html"
    return render(request, template, context)


def control_newsletter(request):
    form = NewsletterCreationForm(request.POST or None)

    if form.is_valid():
        instance = form.save()
        newsletter = Newsletter.objects.get(id=instance.id)
        if newsletter.status == "Published":
            subject = newsletter.subject
            body = newsletter.body
            from_email = settings.EMAIL_HOST_USER
            for email in newsletter.email.all():
                send_mail(subject=subject, from_email=from_email, recipient_list=[
                          email], message=body, fail_silently=False)
    context = {
        "form": form,
    }
    template = 'control_newsletter.html'
    return render(request, template, context)


def control_newsletter_list(request):
    newsletter = Newsletter.objects.all()
    paginator = Paginator(newsletter, 10)
    page = request.GET.get('page')

    try:
        items = paginator.page(page)
    except PageNotAnInteger:
        items = paginator.page(1)
    except EmptyPage:
        items = paginator.page(paginator.num_pages)

    index = items.number - 1
    max_index = len(paginator.page_range)
    start_index = index - 5 if index >= 5 else 0
    end_index = index + 5 if index <= max_index - 5 else max_index
    page_range = paginator.page_range[start_index:end_index]

    context = {
        "items": items,
        "page_range": page_range
    }
    template = "control_newsletter_list.html"
    return render(request, template, context)


def control_newsletter_detail(request, pk):
    newsletter = get_object_or_404(Newsletter, pk=pk)
    context = {
        "newsletter": newsletter,
    }
    template = "control_newsletter_detail.html"
    return render(request, template, context)


def control_newsletter_edit(request, pk):
    newsletter = get_object_or_404(Newsletter, pk=pk)

    if request.method == 'POST':
        form = NewsletterCreationForm(request.POST, instance=newsletter)

        if form.is_valid():
            newsletter = form.save()

            if newsletter.status == "Published":
                subject = newsletter.subject
                body = newsletter.body
                from_email = settings.EMAIL_HOST_USER
                for email in newsletter.email.all():
                    send_mail(subject=subject, from_email=from_email, recipient_list=[
                        email], message=body, fail_silently=False)

            return redirect('control_panel:control_newsletter_detail', pk=newsletter.pk)
    else:
        form = NewsletterCreationForm(instance=newsletter)
    context = {
        "form": form,
    }
    template = 'control_newsletter.html'
    return render(request, template, context)


def control_newsletter_delete(request, pk):
    newsletter = get_object_or_404(Newsletter, pk=pk)

    if request.method == 'POST':
        form = NewsletterCreationForm(request.POST, instance=newsletter)

        if form.is_valid():
            newsletter.delete()

            return redirect('control_panel:control_newsletter_list')
    else:
        form = NewsletterCreationForm(instance=newsletter)
    context = {
        "form": form,
    }
    template = 'control_newsletter_delete.html'
    return render(request, template, context)

Here is the models.py


class NewsletterUser(models.Model):
    email = models.EmailField()
    date_added = models.DateTimeField(default=timezone.now)

    class Meta:
        verbose_name = "Newsletter User"

    def __str__(self):
        return self.email


class Newsletter(models.Model):
    EMAIL_STATUS_CHOICES = (
        ('Draft', 'Draft'),
        ('Published', 'Published')
    )
    subject = models.CharField(max_length=250)
    body = models.TextField()
    email = models.ManyToManyField(NewsletterUser)
    status = models.CharField(max_length=10, choices=EMAIL_STATUS_CHOICES)
    created = models.DateTimeField(default=timezone.now)
    updated = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.subject
Submitted on Jun 20, 20
add a comment

1 Answer

Acknowledged. We will take a look on this and get back to you.

Submitted 4 years, 3 months ago

Could you please elaborate "I am sure that the email setting is correct as I am receiving an email after a successful subscription for testing."?. If its working for testing then may i know where is not working?

- bhavana 4 years, 3 months ago

the control_newsletter function ```def control_newsletter(request): form = NewsletterCreationForm(request.POST or None)

if form.is_valid():
    instance = form.save()
    newsletter = Newsletter.objects.get(id=instance.id)
    if newsletter.status == "Published":
        subject = newsletter.subject
        body = newsletter.body
        from_email = settings.EMAIL_HOST_USER
        for email in newsletter.email.all():
            send_mail(subject=subject, from_email=from_email, recipient_list=[
                      email], message=body, fail_silently=False)
context = {
    "form": form,
}
template = 'control_newsletter.html'
return render(request, template, context)

```

- ahmed.hisham87 4 years, 3 months ago

The email is not being sent in the control_newsletter function

- ahmed.hisham87 4 years, 3 months ago

can you check this in for email in newsletter.email.all(): print(email)?

- bhavana 4 years, 3 months ago

nothing gets printed

- ahmed.hisham87 4 years, 3 months ago

I have also set the fail_silently=False so that I can receive an error but I am not receiving anything

- ahmed.hisham87 4 years, 3 months ago

so which mean there is no output in the for loop right?

- bhavana 4 years, 3 months ago

how do I fix that ?

- ahmed.hisham87 4 years, 3 months ago

Can you check at least form is valid & print(some thing) in for loop and make sure. its pass through the for loop or not.

- bhavana 4 years, 3 months ago

can you please check it?

- bhavana 4 years, 3 months ago

I'm not sure I know how to do it, Could you explain how to check it?

- ahmed.hisham87 4 years, 3 months ago

if form.is_valid(): instance = form.save() newsletter = Newsletter.objects.get(id=instance.id) if newsletter.status == "Published": subject = newsletter.subject body = newsletter.body print(newsletter.email) from_email = settings.EMAIL_HOST_USER for email in newsletter.email.all(): send_mail(subject=subject, from_email=from_email, recipient_list=[ email], message=body, fail_silently=False) context = { "form": form, } template = 'control_newsletter.html' return render(request, template, context)

- bhavana 4 years, 3 months ago

I dont know what is the difference between your code and mine other than the print test but actually it is working now

- ahmed.hisham87 4 years, 3 months ago

ah awesome. Glad to hear :)

- bhavana 4 years, 3 months ago


Latest Blogs