如何使用celery和dajngo发送带图片附件的邮件?

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

我想使用 celery 发送带有照片的电子邮件,但我收到“字节类型的对象不是 JSON 序列化”错误。我只是不明白如何正确地做到这一点。据我所知,芹菜不支持字节。但我试图将它转换为字符串并得到其他错误。

views.py

from main_app.tasks import send_creator_submission_email_task


class BecomeCreatorView(TemplateView):
    template_name = 'become_creator.html'
    become_creator_form = BecomeCreatorForm
    success_url = reverse_lazy('index')

    def get(self, request, *args, **kwargs):
        form = self.become_creator_form()
        return render(request, self.template_name, {'form': form})

    def post(self, request, *args, **kwargs):
        form = self.become_creator_form(request.POST, request.FILES)
        if form.is_valid():
            photo = form.cleaned_data['photo']
            send_creator_submission_email_task.delay(self.kwargs.get('slug'), photo.file, photo.name)
            messages.success(request, "Thank you!")
            return redirect(self.success_url)
        messages.error(request, "Error!")
        return render(request, self.template_name, {'form': form})

tasks.py

@shared_task
def send_creator_submission_email_task(slug, image_file, image_filename):
    return send_creator_submission_email(slug, image_file, image_filename)

电子邮件.py

def send_creator_submission_email(slug, image_file, image_filename):
    user = get_object_or_404(User, slug=slug)
    current_site = Site.objects.get_current().domain

    email_context = {
        'current_site': current_site,
        'user_email': user.email,
        'user_slug': user.slug,
        'approve_url': f"http://{current_site}{reverse_lazy('approve_user', kwargs={'slug': user.slug})}",
        "decline_url": f"http://{current_site}{reverse_lazy('decline_user', kwargs={'slug': user.slug})}"
    }

    html_message = render_to_string('email/admin_decision_email.html', email_context)
    plain_message = strip_tags(html_message)

    email = EmailMultiAlternatives(
        subject="New creator submission",
        body=plain_message,
        from_email=settings.DEFAULT_FROM_EMAIL,
        to=[settings.EMAIL_ADMIN],
    )

    email.attach_alternative(html_message, "text/html")
    email.attach(image_filename, image_file.read())
    email.send()

如果您想重新创建案例,这些文件适合您: forms.py

class BecomeCreatorForm(forms.Form):
    photo = forms.ImageField(
        required=True,
        widget=forms.ClearableFileInput
    )

admin_decision_email.html

{% autoescape off %}

<p>New user photo submission from: {{ user_email }}</p>
<p>User slug: {{ user_slug }}</p>
<p>Please approve or decline the attached photo.</p>

<p>Actevate: {{ approve_url }}</p>
<p>Decline: {{ decline_url }}</p>

{% endautoescape %}
python django celery
© www.soinside.com 2019 - 2024. All rights reserved.