0

I am trying to send newsletters as emails to the subscribed users. For that, I did:

I made a Custom send_mail() function within my model to send emails to subscribed users

class Post(models.Model):

    'model fields here'


    def __str__(self):
        return self.title + ' by ' + self.author


    def send_mail(self, request):
        content = self.content
        title = self.title
        slug = self.slug
        series_name = self.series_name
        confirmed_subscribers = Subscriber.objects.values_list('email').filter(confirmed=True)
        current_site = get_current_site(request)
        subject = "New Blog - '" + title + "' @ AM-Blogs!!"
        message = render_to_string('new_post.html',{
                'title': title,
                'content': content,
                'slug': slug,
                'series_name': series_name,
                'domain': current_site.domain,
            })

        for sub in confirmed_subscribers:

            email = EmailMessage(
            subject,
            message,
            settings.EMAIL_HOST_USER,
            [sub],
            )
            email.fail_silently = True
            email.send()

        return redirect ('Home')

Then, in admin.py:

class PostAdmin(admin.ModelAdmin):

    class Media:
        js = ('tinyInject.js',)

    actions = ['send_mail']

    def send_mail(self, request, queryset):
        for post in queryset:
            post.send_mail(request)
    send_mail.short_description = "Send selected Newsletters to all subscribers"




admin.site.register(Post, PostAdmin)

And when I got to my admin panel and perform the action:

Error:

ValueError at /admin/blog/post/
not enough values to unpack (expected 2, got 1)

Highlighted Error:

D:\My_Projects\My-Blog\blog\admin.py in send_mail
            post.send_mail(request) …
▶ Local vars
D:\My_Projects\My-Blog\blog\models.py in send_mail
            email.send() …
▶ Local vars

How can I solve this issue? Please help!!

Anubhav Madhav
  • 173
  • 2
  • 9

1 Answers1

0

Okay!! I have solved it myself. The only mistake here was that the 'to_email'(receivers of the email) - subscribers is itself a list.

the code should be something like:

emailsub = EmailMessage(
                subject,
                message,
                settings.EMAIL_HOST_USER,
                sub,
                )

instead of:

emailsub = EmailMessage(
                subject,
                message,
                settings.EMAIL_HOST_USER,
                [sub],
                )

Thank You!!

Anubhav Madhav
  • 173
  • 2
  • 9