Django - 两次发送电子邮件

时间:2014-05-07 16:10:01

标签: python django email

每当我使用下面显示的电子邮件设置从views.py调用下面的方法时,会将两封电子邮件副本发送给收件人,我收到如下错误:

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'

1 个答案:

答案 0 :(得分:2)

浏览器通常会向他们可以找到的任何网址发送HEAD请求。如果Django对HEAD请求进行操作,那么再次在下面的GET请求中,您将看到函数被调用两次。

考虑将“发送邮件”功能移至POST请求,或仅在真实GET上发送电子邮件,而不是其他任何内容。

未测试:

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/