Django - 电子邮件发送两次 [英] Django - Email sending twice

查看:145
本文介绍了Django - 电子邮件发送两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我通过以下电子邮件设置调用下面的方法,请将以下电子邮件设置的两个副本发送给收件人,并显示如下错误:

Whenever I call the method below from views.py with the email settings shown below, two copies of the email are sent to the recipient and I get the error shown below:

def sendEmailBasic(request):
   msg = EmailMessage('Request Callback',
                      'Here is the message.', to=['example@gmail.com'])
    msg.send() 
    return HttpResponseRedirect('/')


Exception happened during processing of request from ('127.0.0.1', 58207)
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 593, in process_request_thread
self.finish_request(request, client_address)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 334, in finish_request
self.RequestHandlerClass(request, client_address, self)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 150, in __init__
super(WSGIRequestHandler, self).__init__(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 651, in __init__
self.finish()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 710, in finish
self.wfile.close()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 279, in close
self.flush()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 303, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe


DEFAULT_FROM_EMAIL = 'myemail@gmail.com'
SERVER_EMAIL = 'myemail@gmail.com'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'myemail@gmail.com'
EMAIL_HOST_PASSWORD = 'my password'


推荐答案

浏览器通常会发送HEAD请求他们可以找到的任何URL。如果Django在HEAD请求上运行,则再次按照以下GET请求,您将看到两次调用的函数。

Browsers will often send a HEAD request to any URL they can find. If Django operates on the HEAD request, then again on the following GET request, you'll see functions being called twice.

考虑将发送邮件功能移到POST请求,或只发送电子邮件到真正的GET,而不是任何其他东西。

Consider moving the "send mail" function to a POST request, or only send email on a real GET, not anything else.

未测试:

def sendEmailBasic(request):
   if request.method in ('GET', 'POST'):
       msg = EmailMessage('Request Callback',
                      'Here is the message.', to=['example@gmail.com'])
       msg.send() 
   return HttpResponseRedirect('/')

另请参见: http: /restcookbook.com/HTTP%20Methods/idempotency/

这篇关于Django - 电子邮件发送两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆