Forums

raise SMTPServerDisconnected("Connection unexpectedly closed") / smtplib.SMTPServerDisconnected: Connection unexpectedly closed

I am able to send emails with SMTP to verify users after registration, the code works fine when I test. But the same code doesn't work if new user registers after an hour or 30mins, no emails are sent to them to verify.

I am getting the below logs. 2023-08-02 10:02:14,523: raise SMTPServerDisconnected("Connection unexpectedly closed") 2023-08-02 10:02:14,524: smtplib.SMTPServerDisconnected: Connection unexpectedly closed.

The email verification for concurrent user registrations fails with the same error. I had to manually reload the webapp every time user registration for them to get the email with SMTP setting.

Please let me know if there are ways to reload the webapp after user registration?

That sounds like you're relying on the SMTP connection to remain open. Make sure you're creating a new connection each time you're sending the email instead of trying to use the old connection.

I used EMAIL_TIMEOUT settings but that didn't work for concurrent user registration verification. Is there a function known to create a new SMTP connections rather than using an existing one for send_email ?

def register_request(request): form = UserRegistrationForm()

if request.method == 'POST':
    form = UserRegistrationForm(request.POST)

    if form.is_valid():
        form.save(commit=False)
        user_email = form.cleaned_data['email']
        user_username = form.cleaned_data['username']
        user_password = form.cleaned_data['password1']

        # Create new user
        user = User.objects.create_user(username=user_username, email=user_email, password=user_password)

        # Make user unactive until they click link to token in email
        user.is_active = False
        send_email(user)

Is the error coming from the send_email function?

Below are the error logs, looks like it is waiting for the reply from SMTP server. Could this be an issue with the SMTP provider?

File "/usr/lib/python3.8/smtplib.py", line 757, in starttls (resp, reply) = self.docmd("STARTTLS") File "/usr/lib/python3.8/smtplib.py", line 425, in docmd return self.getreply() File "/usr/lib/python3.8/smtplib.py", line 398, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") smtplib.SMTPServerDisconnected: Connection unexpectedly closed

Yes, that certainly looks like the SMTP server is closing the connection -- it's happening specifically while the SMTP library is configuring the encryption on the connection (STARTTLS). It's possible that the server that you're connecting to is configured to drop connections from cloud environments, or something like that -- I'd recommend reaching out to the server's administrators to see if that's what's happening.