When i'm trying setup send_mail in production, I got "ConnectionRefusedError "

I’m a newbie in Django. Last few days I’m trying to establish Django send_mail in production from Cpane. all working in localhost, but when I’ve put these codes into the live website, it’s not working. I’m getting the same error again and again. Can you please help to out of this problem?

# ConnectionRefusedError at /

[Errno 111] Connection refused

|Request Method:|POST|
| — | — |
|Request URL:|https://portfolio.service-shakil.com/|
|Django Version:|3.2.6|
|Exception Type:|ConnectionRefusedError|
|Exception Value:|[Errno 111] Connection refused|
|Exception Location:|/opt/alt/python37/lib64/python3.7/socket.py, line 716, in create_connection|
|Python Executable:|/home/services/virtualenv/portfolio-shakil/3.7/bin/python3.7|
|Python Version:|3.7.10|
|Python Path:|[’’, ‘/home/services/portfolio-shakil’, ‘/home/services/virtualenv/portfolio-shakil/3.7/lib64/python37.zip’, ‘/home/services/virtualenv/portfolio-shakil/3.7/lib64/python3.7’, ‘/home/services/virtualenv/portfolio-shakil/3.7/lib64/python3.7/lib-dynload’, ‘/opt/alt/python37/lib64/python3.7’, ‘/opt/alt/python37/lib/python3.7’, ‘/home/services/virtualenv/portfolio-shakil/3.7/lib/python3.7/site-packages’]|
|Server time:|Wed, 18 Aug 2021 19:15:26 +0000|

I’m guessing this is the error you’re seeing in your browser (as opposed to the error messages in the logs on the server). If you can get the full traceback from the server logs, that would be more helpful.

As it is, if you would post your view that is throwing this error, we might be able to see something in it. (This is likely to be just the start. We may need to ask many questions to drill down to find the exact cause of the error.)

It may also be helpful to see your settings that are associated with the recent set of changes (email settings in particular, except for your account’s password).

Hi sir@KenWhitesell Thanks for your response, I’m getting this error log,

Environment:


Request Method: POST
Request URL: https://portfolio.service-shakil.com/

Django Version: 3.2.6
Python Version: 3.7.10
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'portfolio_shakil_app']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "/home/services/virtualenv/portfolio-shakil/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/services/virtualenv/portfolio-shakil/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/services/portfolio-shakil/portfolio_shakil_app/views.py", line 31, in index
    send_mail(data['subject'], message, 'shakil.cse.uoda@gmail.com', ['shakil.gd13@gmail.com'], fail_silently=False, auth_user='None', auth_password=None, connection=None, html_message=None)
  File "/home/services/virtualenv/portfolio-shakil/3.7/lib/python3.7/site-packages/django/core/mail/__init__.py", line 61, in send_mail
    return mail.send()
  File "/home/services/virtualenv/portfolio-shakil/3.7/lib/python3.7/site-packages/django/core/mail/message.py", line 284, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "/home/services/virtualenv/portfolio-shakil/3.7/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages
    new_conn_created = self.open()
  File "/home/services/virtualenv/portfolio-shakil/3.7/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 62, in open
    self.connection = self.connection_class(self.host, self.port, **connection_params)
  File "/opt/alt/python37/lib64/python3.7/smtplib.py", line 251, in __init__
    (code, msg) = self.connect(host, port)
  File "/opt/alt/python37/lib64/python3.7/smtplib.py", line 336, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/opt/alt/python37/lib64/python3.7/smtplib.py", line 307, in _get_socket
    self.source_address)
  File "/opt/alt/python37/lib64/python3.7/socket.py", line 728, in create_connection
    raise err
  File "/opt/alt/python37/lib64/python3.7/socket.py", line 716, in create_connection
    sock.connect(sa)

Exception Type: ConnectionRefusedError at /
Exception Value: [Errno 111] Connection refused

We will need to see the view and the corresponding settings from your settings file.

It’s possible that this might be some type of configuration error. It could be that the system has a firewall active, preventing outbound connections on that port. It could be the ISP restricts connections on that port. It could be that the email server is rejecting inbound connections from your IP address.

It’s hard to say without seeing more details.

Side note: When posting code, templates, error messages, etc, please enclose them between lines of three backtick - ` characters. That means you’ll have a line of ```, then your code/errors/etc, then another line of ```. This forces the forum software to maintain the proper formatting of the code, which is critical with Python.

I got this stderr.log, Please check below,

Internal Server Error: /
Traceback (most recent call last):
  File "/home/services/virtualenv/portfolio-shakil/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/services/virtualenv/portfolio-shakil/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/services/portfolio-shakil/portfolio_shakil_app/views.py", line 31, in index
    send_mail(data['subject'], message, 'shakil.cse.uoda@gmail.com', ['shakil.gd13@gmail.com'], fail_silently=False,)
  File "/home/services/virtualenv/portfolio-shakil/3.7/lib/python3.7/site-packages/django/core/mail/__init__.py", line 61, in send_mail
    return mail.send()
  File "/home/services/virtualenv/portfolio-shakil/3.7/lib/python3.7/site-packages/django/core/mail/message.py", line 284, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "/home/services/virtualenv/portfolio-shakil/3.7/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages
    new_conn_created = self.open()
  File "/home/services/virtualenv/portfolio-shakil/3.7/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 62, in open
    self.connection = self.connection_class(self.host, self.port, **connection_params)
  File "/opt/alt/python37/lib64/python3.7/smtplib.py", line 251, in __init__
    (code, msg) = self.connect(host, port)
  File "/opt/alt/python37/lib64/python3.7/smtplib.py", line 336, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/opt/alt/python37/lib64/python3.7/smtplib.py", line 307, in _get_socket
    self.source_address)
  File "/opt/alt/python37/lib64/python3.7/socket.py", line 728, in create_connection
    raise err
  File "/opt/alt/python37/lib64/python3.7/socket.py", line 716, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

sir, this is my view file

def index(request):

        latest_work_data = portfolio_work.objects.order_by('-portfolio_dateTime')

        if request.method == "POST":
            name = request.POST['contactName']
            email = request.POST['contactEmail']
            subject = request.POST['contactSubject']
            message = request.POST['contactMessage']


            data = {
                'name':name,
                'email':email,
                'subject':subject,
                'message':message,
            }
            message = '''
            name:{}
            New Message:{}
            From:{}
            '''.format(data['name'],data['message'], data['email'])

            send_mail(data['subject'], message, 'shakil.cse.uoda@gmail.com', ['shakil.gd13@gmail.com'], fail_silently=False,)
        return render(request, 'index.html', {'latest_work_data':latest_work_data})

Sir, this is my view file,

from django.http.response import HttpResponse
from django.shortcuts import render
from django.core.mail import send_mail
from .models import portfolio_work

# Create your views here.

def index(request):

        latest_work_data = portfolio_work.objects.order_by('-portfolio_dateTime')

        if request.method == "POST":
            name = request.POST['contactName']
            email = request.POST['contactEmail']
            subject = request.POST['contactSubject']
            message = request.POST['contactMessage']


            data = {
                'name':name,
                'email':email,
                'subject':subject,
                'message':message,
            }
            message = '''
            name:{}
            New Message:{}
            From:{}
            '''.format(data['name'],data['message'], data['email'])

            send_mail(data['subject'], message, 'shakil.cse.uoda@gmail.com', ['shakil.gd13@gmail.com'], fail_silently=False,)
        return render(request, 'index.html', {'latest_work_data':latest_work_data})

my setting file,

"""
Django settings for portfolio_shakil_project project.

Generated by 'django-admin startproject' using Django 3.2.6.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'secret key'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['portfolio.service-shakil.com','http://portfolio.service-shakil.com/','www.portfolio.service-shakil.com/']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'portfolio_shakil_app',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'portfolio_shakil_project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'portfolio_shakil_project.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': '',                  
        'USER': '',             
        'PASSWORD': '',                  
        'HOST': '',                     
        'PORT': '',                      
    }
}

# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

#cookie secure 
CSRF_COOKIE_SECURE = False


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = '/static/'

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'shakil.cse.uoda@gmail.com'
EMAIL_HOST_PASSWORD = used 16 digit app password
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False

To clarify, this is your gmail password for that account (shakil.cse.uoda@gmail.com) and not a password for your Django system, correct?

Can you verify that you can log into gmail with those credentials?

yes, sir, It’s my Gmail password. At the development level, it was working and I’m getting mail. but after upload files into production, getting this error.

Then I have to come back to this:

I’d check all available documentation from your hosting provider to determine whether or not there are any restrictions in place regarding port 587.

which document should i send you for checking this problem?
I take my hosting from https://www.dhakawebhost.com/

That’s something you need to research with them.

Since you’re saying that this works for you in a development environment, with the same settings, then I find it unlikely at this point to be a Django issue. It certainly appears to be something with your hosting provider.

1 Like

Okay, sir, I will contact them and will get back to you with what they said. Thank you very much :heart: for your valuable time.