【问题标题】:Django:Send email after redirectDjango:重定向后发送电子邮件
【发布时间】:2020-04-23 18:59:09
【问题描述】:

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

views.py

选项 1:在“重定向”之前放置“发送邮件”

    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,保存表单集但不发送电子邮件。 有没有办法在重定向后发送电子邮件,以便用户在页面重定向之前无需等待电子邮件处理?

谢谢。

【问题讨论】:

    标签: django django-forms django-views django-templates


    【解决方案1】:

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

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

    【讨论】:

    • 标准的 django send_mail() 确实有效。我将“EMAIL_HOST_USER”更改为“settings.EMAIL_HOST_USER”。我的导入不正确。但我决定和芹菜一起去,它也很管用。谢谢你的建议。
    • 标准的 django send_mail() 确实有效 - 我的观点是选项 2 不起作用,因为返回后的代码没有运行。
    猜你喜欢
    • 2015-10-01
    • 2019-06-09
    • 2018-01-17
    • 1970-01-01
    • 2019-12-15
    • 1970-01-01
    • 2021-03-08
    • 2011-10-18
    • 2020-08-17
    相关资源
    最近更新 更多