pypy_test
pypy_test

Reputation: 11

python sending email - ConnectionRefusedError: [Errno 111] Connection refused. Please suggest some ideas

I wrote a basic function in python to send email using smtp with localhost, but it keeps on failing, however another script is working fine with the same code.

my function:


def send_email_err():

    sender = '[email protected]'
    receivers = ['[email protected]']

    message = """From: From Person <[email protected]>
    To: To Person <[email protected]>
    Subject: SMTP e-mail test

    This is a test e-mail message.
    """

    try:
        smtpObj = smtplib.SMTP('localhost')
        smtpObj.sendmail(sender, receivers, message)
        print ("Successfully sent email")
    except SMTPException:
        print ("Error: unable to send email")

send_email_err()

The error I'm getting is:


    Traceback (most recent call last):
  File "./send_email.py", line 147, in send_email_err
    smtpObj = smtplib.SMTP('localhost')
  File "/usr/lib64/python3.6/smtplib.py", line 251, in __init__
    (code, msg) = self.connect(host, port)
  File "/usr/lib64/python3.6/smtplib.py", line 336, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/usr/lib64/python3.6/smtplib.py", line 307, in _get_socket
    self.source_address)
  File "/usr/lib64/python3.6/socket.py", line 724, in create_connection
    raise err
  File "/usr/lib64/python3.6/socket.py", line 713, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "./send_email.py", line 159, in <module>
    send_email_err()
  File "./send_email.py", line 150, in send_email_err
    except SMTPException:
NameError: name 'SMTPException' is not defined

Do we need smtp server running on the host where I execute this script to be able to send out this email.

Upvotes: 1

Views: 2560

Answers (2)

Janus
Janus

Reputation: 21

  • First tb: You forgot to start the server. Spin a second terminal and run python -m smtpd -n -c DebuggingServer host:port if you're running it on your local device AND testing the functionality

  • Second Error: You forgot to import SMTPException from smtplib import SMTPException

You're tensed, relax :)

Upvotes: 1

Edward Casanova
Edward Casanova

Reputation: 954

Nowadays it is recommended to use https://aiosmtpd.readthedocs.io/en/latest/cli.html instead.

Because of:

deprecationWarning: The asynchat module is deprecated and will be removed in Python 3.12. The recommended replacement is asyncio

Upvotes: -1

Related Questions