I keep getting this intermittent error when trying to send through 'smtp.gmail.com'.
Traceback (most recent call last):
File "/var/home/ptarjan/django/mysite/django/core/handlers/base.py", line 92, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/var/home/ptarjan/django/mysite/registration/views.py", line 137, in register
new_user = form.save()
File "/var/home/ptarjan/django/mysite/registration/forms.py", line 79, in save
email=self.cleaned_data['email'])
File "/var/home/ptarjan/django/mysite/django/db/transaction.py", line 240, in _commit_on_success
res = func(*args, **kw)
File "/var/home/ptarjan/django/mysite/registration/models.py", line 120, in create_inactive_user
registration_profile.send_registration_mail()
File "/var/home/ptarjan/django/mysite/registration/models.py", line 259, in send_registration_mail
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [self.user.email])
File "/var/home/ptarjan/django/mysite/django/core/mail.py", line 390, in send_mail
connection=connection).send()
File "/var/home/ptarjan/django/mysite/django/core/mail.py", line 266, in send
return self.get_connection(fail_silently).send_messages([self])
File "/var/home/ptarjan/django/mysite/django/core/mail.py", line 172, in send_messages
sent = self._send(message)
File "/var/home/ptarjan/django/mysite/django/core/mail.py", line 186, in _send
email_message.message().as_string())
File "/usr/lib/python2.5/smtplib.py", line 704, in sendmail
(code,resp) = self.data(msg)
File "/usr/lib/python2.5/smtplib.py", line 484, in data
(code,repl)=self.getreply()
File "/usr/lib/python2.5/smtplib.py", line 352, in getreply
line = self.file.readline()
File "/usr/lib/python2.5/smtplib.py", line 160, in readline
chr = self.sslobj.read(1)
sslerror: The read operation timed out
I'm running Django 1.1 with the django-registarion app. With these in my settings.py
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = "**SECRET**"
EMAIL_HOST_PASSWORD = "**SECRET**"
EMAIL_PORT = 587
EMAIL_USE_TLS = True
Altho' I don't know why, I have been thro' this, and it works when you have settings variables ordered in a particular order:
EMAIL_HOST
EMAIL_PORT
EMAIL_HOST_USER
EMAIL_HOST_PASSWORD
EMAIL_USE_TLS
Looks like gmail may simply be occasionally slow to respond, so your operation times out. Perhaps you can use a try/except to catch such issues and retry a few times (maybe waiting a while between attempts). BTW, this task seems well suited to a dedicated or pooled thread which encapsulates the whole "send mail with retries" operation.
Related
I am trying to send e-mails through my Gmail account for my Django application. I'm using below configurations in settings.py file.
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST_USER = 'username#gmail.com'
EMAIL_HOST = 'smtp.gmail.com' # tried smtp-relay.gmail.com also
EMAIL_PORT = '587'
EMAIL_USE_TLS = True
EMAIL_HOST_PASSWORD = 'Gmail password / app password'
Import statements in this regard:
from django.core.mail import send_mail, EmailMessage
from django.conf import settings
Following is in my views function:
message = EmailMessage(subject=email_subject, body=email_message, from_email=settings.EMAIL_HOST_USER, to=[email, 'username#gmail.com'])
message.send(fail_silently=False)
I have tried this also:
send_mail(email_subject, email_message , settings.EMAIL_HOST_USER, [email, 'username#gmail.com'] , fail_silently=False, )
Any help is much appreciated. Please note that I have tried:
enabling less secure apps button in Gmail
Then, I disabled less secure apps, enabled 2 factor authentication and use app passwords option of Google.
Here is the complete traceback:
Traceback (most recent call last):
File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/jatinsinghbhati/Documents/workspaces/pollsite/signup/views.py", line 40, in index
message.send(fail_silently=False)
File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/core/mail/message.py", line 284, in send
return self.get_connection(fail_silently).send_messages([self])
File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages
new_conn_created = self.open()
File "/Users/jatinsinghbhati/Documents/workspaces/djangoenv/lib/python3.9/site-packages/django/core/mail/backends/smtp.py", line 62, in open
self.connection = self.connection_class(self.host, self.port, **connection_params)
File "/Users/jatinsinghbhati/.pyenv/versions/3.9.0/lib/python3.9/smtplib.py", line 253, in __init__
(code, msg) = self.connect(host, port)
File "/Users/jatinsinghbhati/.pyenv/versions/3.9.0/lib/python3.9/smtplib.py", line 339, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/Users/jatinsinghbhati/.pyenv/versions/3.9.0/lib/python3.9/smtplib.py", line 310, in _get_socket
return socket.create_connection((host, port), timeout,
File "/Users/jatinsinghbhati/.pyenv/versions/3.9.0/lib/python3.9/socket.py", line 843, in create_connection
raise err
File "/Users/jatinsinghbhati/.pyenv/versions/3.9.0/lib/python3.9/socket.py", line 831, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 61] Connection refused
[25/Feb/2021 19:38:20] "POST /signup/ HTTP/1.1" 500 101708
It should be
EMAIL_PORT = 587
But not
EMAIL_PORT = '587'
PORT number is an integer not a string.
Please i have been facing this error for the past three days , i have already checked all answers and i have made appropriate corrections, allowed less secure apps, off 2 factor authentication, cross checked username/password
But non of these help
settings.py code
SERVER_EMAIL = 'infopython#gmail.com'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_HOST_USER = SERVER_EMAIL
EMAIL_PORT = 587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
ADMINS = [
('admin', 'admin5#gmail.com'),
]
MANAGERS = ADMINS
Output
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line
utility.execute()
File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 335, in execute
output = self.handle(*args, **options)
File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\sendtestemail.py", line 33, in handle
recipient_list=kwargs['email'],
File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\mail\__init__.py", line 60, in send_mail
return mail.send()
File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\mail\message.py", line 294, in send
return self.get_connection(fail_silently).send_messages([self])
File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\mail\backends\smtp.py", line 103, in send_messages
new_conn_created = self.open()
File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\mail\backends\smtp.py", line 63, in open
self.connection = self.connection_class(self.host, self.port, **connection_params)
File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python37-32\lib\smtplib.py", line 254, in __init__
raise SMTPConnectError(code, msg)
smtplib.SMTPConnectError: (451, b'Request action aborted on MFE proxy, SMTP server is not available.')
I got this error when mail port was set to 25
EMAIL_PORT = 25
I had to change the port for it to work for me. Do check if your email host provides other ports and try any other available ports.
For me, changing the email port from 25 to 587 worked.
EMAIL_PORT = 587
I'm trying to set up self-serve password resets on a django setup. I have configured it to use the in-built password reset system, and have tested everything on my dev machine, and works fine. However, in production (i.e. actually sending emails), when I try to get a password reset email, it throws an SMTPServerDisconnected error:
[22/Sep/2017 15:04:59] ERROR [django.request:256] Internal Server Error: /password_reset/
Traceback (most recent call last):
File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/utils/decorators.py", line 145, in inner
return func(*args, **kwargs)
File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/utils/decorators.py", line 110, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/contrib/auth/views.py", line 182, in password_reset
form.save(**opts)
File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/contrib/auth/forms.py", line 256, in save
html_email_template_name=html_email_template_name)
File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/contrib/auth/forms.py", line 213, in send_mail
email_message.send()
File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/core/mail/message.py", line 303, in send
return self.get_connection(fail_silently).send_messages([self])
File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 107, in send_messages
sent = self._send(message)
File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 123, in _send
self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n'))
File "/usr/lib/python2.7/smtplib.py", line 735, in sendmail
self.rset()
File "/usr/lib/python2.7/smtplib.py", line 469, in rset
return self.docmd("rset")
File "/usr/lib/python2.7/smtplib.py", line 394, in docmd
return self.getreply()
File "/usr/lib/python2.7/smtplib.py", line 368, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
SMTPServerDisconnected: Connection unexpectedly closed
I'm using G-Suite (Google) as the SMTP relay; the settings I'm using are:
EMAIL_HOST = 'smtp-relay.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
The weird thing is I can send emails fine in other places within the system, using django's django.core.mail.send_mail() function.
The problem turned out to be that I hadn't set DEFAULT_FROM_EMAIL, thus django was attempting to send from a localhost email address, which Google's SMTP servers silently rejected. In other uses for send_mail() I had specified the from address, so this didn't appear as an issue there.
I'm trying to configure a website using Django 1.8 and Plesk, and setting the email variables to any value gets the traceback below. I've tried with Gmail and the email server from the host, and the error is the same. I have tested Python's smtplib and successfully sent an email through that, so it looks like it may be something between Django and Plesk. If I set up the website on a test CentOS 6 server, then I don't run into this problem.
Example Config settings
EMAIL_HOST = "smtp.gmail.com"
EMAIL_HOST_PASSWORD = "mypassword"
EMAIL_HOST_USER = "user#gmail.com"
EMAIL_PORT = 587
Traceback
mod_wsgi (pid=1703): Exception occurred processing WSGI script '/var/www/vhosts/s1085163.instanturl.net/oozoa.wsgi'.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/whitenoise/base.py", line 119, in __call__
return self.application(environ, start_response)
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 189, in __call__
response = self.get_response(request)
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 218, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 256, in handle_uncaught_exception
'request': request
File "/usr/local/lib/python2.7/logging/__init__.py", line 1185, in error
self._log(ERROR, msg, args, **kwargs)
File "/usr/local/lib/python2.7/logging/__init__.py", line 1278, in _log
self.handle(record)
File "/usr/local/lib/python2.7/logging/__init__.py", line 1288, in handle
self.callHandlers(record)
File "/usr/local/lib/python2.7/logging/__init__.py", line 1328, in callHandlers
hdlr.handle(record)
File "/usr/local/lib/python2.7/logging/__init__.py", line 751, in handle
self.emit(record)
File "/usr/local/lib/python2.7/site-packages/django/utils/log.py", line 129, in emit
self.send_mail(subject, message, fail_silently=True, html_message=html_message)
File "/usr/local/lib/python2.7/site-packages/django/utils/log.py", line 132, in send_mail
mail.mail_admins(subject, message, *args, connection=self.connection(), **kwargs)
File "/usr/local/lib/python2.7/site-packages/django/core/mail/__init__.py", line 98, in mail_admins
mail.send(fail_silently=fail_silently)
File "/usr/local/lib/python2.7/site-packages/django/core/mail/message.py", line 303, in send
return self.get_connection(fail_silently).send_messages([self])
File "/usr/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 100, in send_messages
new_conn_created = self.open()
File "/usr/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 58, in open
self.connection = connection_class(self.host, self.port, **connection_params)
File "/usr/local/lib/python2.7/smtplib.py", line 256, in __init__
(code, msg) = self.connect(host, port)
File "/usr/local/lib/python2.7/smtplib.py", line 316, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/local/lib/python2.7/smtplib.py", line 291, in _get_socket
return socket.create_connection((host, port), timeout)
File "/usr/local/lib/python2.7/socket.py", line 557, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
gaierror: [Errno -2] Name or service not known
Might be there is an issues with the firewall. Please try to disabled plesk firewall and IPtables on your server for the testing purpose and check it again.
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'
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.
Consider moving the "send mail" function to a POST request, or only send email on a real GET, not anything else.
Untested:
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('/')
See also: http://restcookbook.com/HTTP%20Methods/idempotency/