微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么Django发送电子邮件功能会发送两次电子邮件?

如何解决为什么Django发送电子邮件功能会发送两次电子邮件?

我已经使用了Django EmailMessage函数
这是views.py文件

def send_bill_mail(request):
    context_dict={
                "name": "abc"
                }
    html_message = render_to_string('home/email_templates/bill_generation.html',context_dict)
    try:
        email = EmailMessage(
            ' Welcome to store',html_message,to=['abc@gmail.com']
            )
        email.content_subtype = "html" 
        email.send()
    except Exception as e:
        messages.error(request,"Something Went Wrong !")
    return redirect('home:dashboard')

这里是settings.py

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'xyz@gmail.com'
EMAIL_HOST_PASSWORD = 'xyz'
EMAIL_PORT = 587

在处理视图期间发生以下异常。

    Exception happened during processing of request from ('127.0.0.1',50522)
Traceback (most recent call last):
  File "C:\Users\sanke\AppData\Local\Programs\Python\python37\lib\socketserver.py",line 650,in process_request_thread
    self.finish_request(request,client_address)
  File "C:\Users\sanke\AppData\Local\Programs\Python\python37\lib\socketserver.py",line 360,in finish_request
    self.RequestHandlerClass(request,client_address,self)
  File "C:\Users\sanke\AppData\Local\Programs\Python\python37\lib\socketserver.py",line 720,in __init__
    self.handle()
  File "C:\Users\sanke\AppData\Local\Programs\Python\python37\lib\site-packages\django\core\servers\basehttp.py",line 174,in handle
    self.handle_one_request()
  File "C:\Users\sanke\AppData\Local\Programs\Python\python37\lib\site-packages\django\core\servers\basehttp.py",line 182,in handle_one_request
    self.raw_requestline = self.rfile.readline(65537)
  File "C:\Users\sanke\AppData\Local\Programs\Python\python37\lib\socket.py",line 589,in readinto
    return self._sock.recv_into(b)
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine

解决方法

当您在本地运行项目时,通常会发生此问题,也许您应该尝试将其托管在Internet上的某个地方

使用连接可以解决以下问题

  def send_bill_mail(request):
        context_dict={
                    "name": "abc"
                    }
        html_message = render_to_string('home/email_templates/bill_generation.html',context_dict)
        email_list = []
        try:
            email = EmailMessage(
                ' Welcome to store',html_message,to=['abc@gmail.com']
                )
            email.content_subtype = "html" 
            email_list.append(email)
            connection = mail.get_connection() 
            connection.send_messages(email_list)
        except Exception as e:
            messages.error(request,"Something Went Wrong !")
        return redirect('home:dashboard')

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。