smtplib.SMTPServerDisconnected: Connection unexpectedly closed and i can't fix it

16 views Asked by At

i use code:

from django.db.models.signals import post_save
from django.dispatch import receiver
from ...models import User as midas_user
from django.core.mail import send_mail
from django.conf import settings
import logging

logger = logging.getLogger(__name__)

@receiver(post_save, sender=midas_user)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        logger.info("New user created: %s", instance.name)
        send_mail("midas_user.instance",
                  "Here is the message",
                  "[email protected]",
                  ["[email protected]"]
                  )

my settings:

EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = "[email protected]"
EMAIL_HOST_PASSWORD = 'i change this string'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

if i try to create user i have error:

shop-backend-back         |   File "/usr/local/lib/python3.8/smtplib.py", line 640, in auth
shop-backend-back         |     (code, resp) = self.docmd("AUTH", mechanism + " " + response)
shop-backend-back         |   File "/usr/local/lib/python3.8/smtplib.py", line 430, in docmd
shop-backend-back         |     return self.getreply()
shop-backend-back         |   File "/usr/local/lib/python3.8/smtplib.py", line 403, in getreply
shop-backend-back         |     raise SMTPServerDisconnected("Connection unexpectedly closed")
shop-backend-back         | smtplib.SMTPServerDisconnected: Connection unexpectedly closed

i just first time try yo use send_mail and take this. how to fix it?

1

There are 1 answers

0
Bret Weinraub On

To use Gmail like this, you will need to follow the instructions shown here:

https://support.google.com/mail/thread/40988320?hl=en

As written there:

If you have two-step verification (2SV) enabled on the account, you will need to use an application specific password (created in the Gmail account) in the app settings: Signing in using application-specific passwords

If 2SV is not enabled, you must enable access for less secure apps: sign into the Gmail account using a web browser at https://mail.google.com, then go to Settings > Accounts and Import > Other Google Account settings. Under Security, scroll down and enable access for less secure apps. This setting is required to enable SMTP, POP or IMAP access.

This article also includes some further troubleshooting steps.

But it is clear from your error, this is not a python issue.