MPsyko
MPsyko

Reputation: 1

Django Sending Email : SMTPServerDisconnected: Connection unexpectedly closed: [WinError 10054] An existing connection was forcibly closed

I am trying to send email to an AOL account via Django and I am getting the following error:

Traceback (most recent call last):
  File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = get_response(request)
  File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Dom\Documents\Python_Projects\Django\TDD_with_Python_and_Django\superlists\accounts\views.py", line 21, in send_login_email
    [email],
  File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\mail\__init__.py", line 62, in send_mail
    return mail.send()
  File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\mail\message.py", line 348, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\mail\backends\smtp.py", line 104, in send_messages
    new_conn_created = self.open()
  File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\mail\backends\smtp.py", line 71, in open
    self.connection.login(force_str(self.username), force_str(self.password))
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python36_64\lib\smtplib.py", line 721, in login
    initial_response_ok=initial_response_ok)
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python36_64\lib\smtplib.py", line 631, in auth
    (code, resp) = self.docmd("AUTH", mechanism + " " + response)
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python36_64\lib\smtplib.py", line 421, in docmd
    return self.getreply()
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python36_64\lib\smtplib.py", line 391, in getreply
    + str(e))
smtplib.SMTPServerDisconnected: Connection unexpectedly closed: [WinError 10054] An existing connection was forcibly closed by the remote host
"POST /accounts/send_email HTTP/1.1" 500 130728

Here are my settings:

EMAIL_HOST = 'smtp.aol.com'
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASSWORD')
EMAIL_PORT = 465
EMAIL_USE_SSL = True

I am following along with the book TDD with Python on Chapter 18, which has a custom authentication backend:

class PasswordlessAuthenticationBackend(object):

    def authenticate(self, uid):
        print('uid', uid, file=sys.stderr)
        if not Token.objects.filter(uid=uid).exists():
            print('no token found', file=sys.stderr)
            return None
        token = Token.objects.get(uid=uid)
        print('got token', file=sys.stderr)
        try:
            user = ListUser.objects.get(email=token.email)
            print('got user', file=sys.stderr)
            return user
        except ListUser.DoesNotExist:
            print('new user', file=sys.stderr)
            return ListUser.object.create(email=token.email)
    

    def get_user(self, email):
        return ListUser.objects.get(email=email)

This is suppose to authenticate the user via email using the following view

def send_login_email(request):
    email = request.POST['email']
    uid = str(uuid.uuid4())
    Token.objects.create(email=email, uid=uid)
    print('saving uid', uid, 'for email', email, file=sys.stderr)
    url = request.build_absolute_uri(f'/accounts/login?uid={uid}')
    send_mail(
        'Your login link for Superlists',
        f'Use this link to log in:\n\n{url}',
        'noreply@superlists',
        [email],
    )
    return render(request, 'login_email_sent.html')

The traceback suggests it is failing at send_login_email but I am not sure why; the book example uses a gmail account but I am using an AOL account instead because I have a throwaway email I never use. I adjusted my settings.py to accommodate AOL's email service settings, but I may have missed something...I'm just not sure what.

Any help/info is greatly appreciated. Thank you.

EDIT I disabled my firewall at the suggestion of @hwjp and I no longer receive the [WinError 10054]; the code gets a little further but now I get the following error:

File "C:\Users\Dom\AppData\Local\Programs\Python\Python36_64\lib\smtplib.py", line 394, in getreply
    raise SMTPServerDisconnected("Connection unexpectedly closed")

Looking at the smtplib.py function where it is failing:

def getreply(self):
        """Get a reply from the server.

        Returns a tuple consisting of:

          - server response code (e.g. '250', or such, if all goes well)
            Note: returns -1 if it can't read response code.

          - server response string corresponding to response code (multiline
            responses are converted to a single, multiline string).

        Raises SMTPServerDisconnected if end-of-file is reached.
        """
        resp = []
        if self.file is None:
            self.file = self.sock.makefile('rb')
        while 1:
            try:
                line = self.file.readline(_MAXLINE + 1)
            except OSError as e:
                self.close()
                raise SMTPServerDisconnected("Connection unexpectedly closed: "
                                             + str(e))
            if not line:
                self.close()
                raise SMTPServerDisconnected("Connection unexpectedly closed")

To me this seems like self.sock.makefile('rb') is failing; but I am not sure why and I am having some difficulties tracing the source of the problem.

I will continue to look into it but any other hints/suggestions are appreciated.

Upvotes: 0

Views: 707

Answers (0)

Related Questions