Please how do I fix this SMTPConnectError Error?

Question:

I am trying to send an email to a user to verify his/her account via an activation link, however when I try to register a user I get the error below. I tried using the send_mail method but it still gives the same error. Please any help will be much appreciated.

My Error

Traceback (most recent call last):
  File "C:UsersDonaldPycharmProjectsto_doAppvenvlibsite-packagesdjangocorehandlersexception.py", line 47, in inner
    response = get_response(request)
  File "C:UsersDonaldPycharmProjectsto_doAppvenvlibsite-packagesdjangocorehandlersbase.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:UsersDonaldPycharmProjectsto_doAppvenvlibsite-packagesdjangoviewsdecoratorscsrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:UsersDonaldPycharmProjectsto_doAppstoreaccountsviews.py", line 44, in register
    send_email.send()
  File "C:UsersDonaldPycharmProjectsto_doAppvenvlibsite-packagesdjangocoremailmessage.py", line 284, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "C:UsersDonaldPycharmProjectsto_doAppvenvlibsite-packagesdjangocoremailbackendssmtp.py", line 102, in send_messages
    new_conn_created = self.open()
  File "C:UsersDonaldPycharmProjectsto_doAppvenvlibsite-packagesdjangocoremailbackendssmtp.py", line 62, in open
    self.connection = self.connection_class(self.host, self.port, **connection_params)
  File "C:UsersDonaldAppDataLocalProgramsPythonPython39libsmtplib.py", line 258, in __init__
    raise SMTPConnectError(code, msg)

Exception Type: SMTPConnectError at /accounts/register/
Exception Value: (421, b'service not available (connection refused, too many connections)')


My views.py

@csrf_exempt
def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            first_name = form.cleaned_data['first_name']
            last_name = form.cleaned_data['last_name']
            phone_number = form.cleaned_data['phone_number']
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            username = email.split('@')[0]
            user = Account.objects.create_user(first_name=first_name, last_name=last_name, email=email, username=username, password=password)
            user.phone_number = phone_number

            #  USER ACTIVATION WITH TOKEN TO EMAIL ACCOUNT
            current_site = get_current_site(request)
            mail_subject = 'Activate your account'
            message = render_to_string('accounts/verification_email.html', {
                'user': user,
                'domain': current_site,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),  # Encode the users primary key
                'token': default_token_generator.make_token(user),
            })
            to_email = email
            send_email = EmailMessage(mail_subject, message, to=[to_email])
            send_email.send()
            user.save()
            messages.success(request, 'Registration Successful')
            return redirect('register')
    else:
        form = RegistrationForm()

    context = {'form': form}
    return render(request, 'accounts/register.html', context)


My settings.py

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'my-email'
EMAIL_HOST_PASSWORD = 'my-password'
EMAIL_USE_TLS = True
Asked By: Donald

||

Answers:

I assume you are using gmail for this. Google seems to be discouraging developers from doing mass mailing from gmail accounts, so I wouldn’t be surprised if you are getting errors. Gmail will inevitably block you from doing this if you use it too much.

I’d recommend trying a service like MailJet or SendInBlue, which is designed for transactional emailing and has much better support and error logging for this purpose. At least it will help you narrow down the problem to the provider.

I recommend http://www.sendinblue.com – it’s quick to set up, and I have had great customer service from them. It’s worth it just to have a free personal test account setup with them for diagnosing these sorts of problems.

Answered By: disconnectionist

Update your email configuration to this.

Ensure you set up an app password on your Gmail account and use the app’s password as EMAIL_HOST_PASSWORD instead of your normal Gmail account password

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 465
EMAIL_HOST_USER = 'my-email'
EMAIL_HOST_PASSWORD = 'my-app-password'
EMAIL_USE_TLS = False
EMAIL_USE_SSL = True

@disconnectionist is right though.

Answered By: FAYEMI BOLUWATIFE
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.