1
votes

So I'm familiar with sending emails using django, but I'd want to send an email to all those that subscribed to my newsletter if I were to use the admin panel instead of the one I have on the site itself. How would I go about doing this? For my current view on the user site version, it is something like:

    def form_valid(self, form):
        message = 'A new article has been released...'
        subject = 'New Article!'
        to = Email.objects.values_list('email', flat=True).distinct()
        from_email = settings.EMAIL_HOST_USER
        send_mail(subject, message, from_email, to, fail_silently=True)

        return super().form_valid(form)
1
What is the problem with this approach?Willem Van Onsem
after a post? the only possibility is to queue email first for some amount oft time say 2 or 3 minutes but if you need some thing synchronous you need to customise the web server your are dealing with to send that email after "tcp" has finished to send this httpresponse...what is a little complicateduser1438644
@WillemVanOnsem well I added CKEditor on the admin panel so that the user (there's only 1 user, the admin himself) can customize the stuff better. With the current on site new post view, it doesn't look as nice as the admin'sworknovel

1 Answers

0
votes

Using django signals will do it via admin or via site doesnt matter.

You can create a signal in blog post view like this:

@receiver(post_save, sender=BlogPost)
def send_mail_to_subs(sender, instance, created, **kwargs):
    if created:
        for subs in instance.author.subscribed.all():
            send_mail(
                f'New Post from {instance.author}',
                f'Title: {instance.post_title}',
                'youremail',
                [subs.email],
            )

Good coding :)