提问人:he1dj 提问时间:8/31/2023 更新时间:8/31/2023 访问量:41
如何在 Django 的同一线程中发送电子邮件?
How to send emails in the same thread in Django?
问:
我想知道如何使用 django.core.mail 在同一个电子邮件线程中发送电子邮件。我有一个 APIView,可以处理来自我的联系表单的帖子请求。它接收联系表单输入并将其发送到我的电子邮件。如果已经使用了表单输入中的电子邮件地址(例如,第一份表单提交时有错误),我希望此类表单在同一个电子邮件线程中发送,而不是在单独的电子邮件中发送。因此,基本上每个线程都应该包含已提交的表单,其电子邮件地址与原始电子邮件的回复相同。
views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import ContactFormSerializer
from rest_framework import status
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.html import strip_tags
class ContactFormAPIView(APIView):
def post(self, request):
serializer = ContactFormSerializer(data=request.data)
if serializer.is_valid():
contact_form = serializer.save()
subject = 'New Contact Form Submitted'
context = {
'name': contact_form.name,
'email': contact_form.email,
'subject': contact_form.subject,
'message': contact_form.message,
'submitted_at': contact_form.submitted_at,
}
html_content = render_to_string('api/contact_form.html', context)
text_content = strip_tags(html_content)
email = EmailMultiAlternatives(
subject, text_content, from_email=settings.EMAIL_HOST_USER, to=[settings.EMAIL_HOST_USER]
)
email.attach_alternative(html_content, 'text/html')
try:
email.send()
except Exception as e:
return Response({'detail': f'Failed to submit the contact form: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
return Response({'detail': 'Contact form submitted successfully.'}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
如果提交了两个具有相同电子邮件地址的联系表单,我的 APIView 只会将它们作为单独的电子邮件发送两次。
当前行为:
期望行为:
每个想法都值得赞赏。
答: 暂无答案
评论