首页 > 解决方案 > Django:重定向后发送电子邮件

问题描述

有没有办法在“返回重定向”之后发送电子邮件?

视图.py

选项 1:在 'redirect' 之前放置 'send_mail'

    if request.method == 'POST':
                formset = TestFormSet(request.POST,request.FILES,instance=project)
                if formset.is_valid():
                    subject = 'Notifications'
                    html_message = "Testing notifications"
                    recipient = ["testingemail@gmail.com"]
                    send_mail(subject, html_message, EMAIL_HOST_USER, [recipient],fail_silently = False)
                    formset.save()
                    return redirect("home")


With Option 1, the email is sent successfully but on the front-end the page has to wait until the email is sent before the redirection takes place.

选项 2:在重定向后放置“send_mail”

 if request.method == 'POST':
                formset = TestFormSet(request.POST,request.FILES,instance=project)
                if formset.is_valid():
                    formset.save()
                    return redirect("home")
                    subject = 'Notifications'
                    html_message = "Testing notifications"
                    recipient = ["testingemail@gmail.com"]
                    send_mail(subject, html_message, EMAIL_HOST_USER, [recipient],fail_silently = False)

使用选项 2,保存表单集但不发送电子邮件。有没有办法在重定向后发送电子邮件,以便用户在重定向页面之前不等待电子邮件处理?

谢谢。

标签: djangodjango-formsdjango-viewsdjango-templates

解决方案


之后的任何代码return都不会运行。一种方法是使用像 celery 这样的任务队列并将电子邮件作为后台任务发送。你可以看看django-mailer。这些方法的缺点是您需要维护一个额外的系统。

您可能会看到一些在单独的线程中发送电子邮件的解决方案,但我会避免使用这些解决方案,因为它们可能很脆弱。


推荐阅读