Django Trying to send (smtp) email but connection refused

Viewed 758

I am using Mac Catalina 10.15.7 / django 3.1.2 / python 3.8.5.

I am trying to send an email from django.

First, I have defined these in settings.py

EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS=True
EMAIL_HOST='smtp.gmail.com'
EMAIL_PORT=587
EMAIL_HOST_USER='MYID@gmail.com'
EMAIL_HOST_PASSWORD='MYPASSWORD'
SERVER_EMAIL='MYID@gmail.com'
DEFAULT_FROM_EMAIL=EMAIL_HOST_USER

and then, I went to the gmail setting and 1) enabled IMAP usage and 2) (in the account's security settings) enabled the usage of the low-security application (https://www.google.com/settings/security/lesssecureapps)

So then, in my pycharms' python console,

from django.core.mail import EmailMessage
email = EmailMessage('subject text', 'body text', to=['RECEIVINGEMAILID@gmail.com'])

but I get these errors:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/Users/capstone1/lib/python3.8/site-packages/django/core/mail/message.py", line 225, in __init__
    self.from_email = from_email or settings.DEFAULT_FROM_EMAIL
  File "/Users/capstone1/lib/python3.8/site-packages/django/conf/__init__.py", line 83, in __getattr__
    self._setup(name)
  File "/Users/capstone1/lib/python3.8/site-packages/django/conf/__init__.py", line 64, in _setup
    raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_FROM_EMAIL, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

so I can't do the next step email.send()

According to the error description, I thought maybe I should use the DJANGO_SETTINGS_MODULE block in settings.py like -

DJANGO_SETTINGS_MODULE = [
    {
    'EMAIL_BACKEND':'django.core.mail.backends.smtp.EmailBackend',
    'EMAIL_USE_TLS':True,
    'EMAIL_PORT':587,
    'EMAIL_HOST':"smtp.gmail.com",
    'EMAIL_HOST_USER':'MYID@gmail.com',
    'EMAIL_HOST_PASSWORD':'MYPASSWORD',
    'SERVER_EMAIL':'MYID@gmail.com',
    'DEFAULT_FROM_EMAIL':"MYID@gmail.com"
    }
]

but it's still giving me the same error.

--

OR, if I do python manage.py shell on terminal,

then,

>>> from django.core.mail import EmailMessage
>>> email = EmailMessage('subject text', 'body text', to=['RECEIVINGEMAILID@gmail.com'])
>>> email.send()

I get these errors:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/capstone1/lib/python3.8/site-packages/django/core/mail/message.py", line 284, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "/Users/capstone1/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages
    new_conn_created = self.open()
  File "/Users/capstone1/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 62, in open
    self.connection = self.connection_class(self.host, self.port, **connection_params)
  File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 253, in __init__
    (code, msg) = self.connect(host, port)
  File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 339, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 308, in _get_socket
    return socket.create_connection((host, port), timeout,
  File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socket.py", line 808, in create_connection
    raise err
  File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socket.py", line 796, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 61] Connection refused

I don't understand why I get the connection refused error because I have set and enabled the Gmail options, or why I get different errors in the python console and python terminal.

(+ I heard that Django already has SMTP installed, so I haven't done anything else.)

What should I do?

1 Answers

In the python shell, you will have to declare DJANGO_SETTINGS_MODULE before you can access the Django modules like SendEmail.
Why you get a connection refused error? It can be you are using 2fa on your account or haven't switched off the less secure app.

Try running the below view function by attaching it to a URL in urls.py.

from django.core.mail import EmailMessage

def SendEmail():
    status = False
    try:
        email = EmailMessage("test", "test", to=['yourid@email.com'])
        email.send()
        status = True
    except Exception as e:
        print(e)    
    return status

In your settings.py define email settings like below you have defined as a dict

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'yourid@email.com'
EMAIL_HOST_PASSWORD = 'pwd'
EMAIL_PORT = 587    
Related