jackfromperu
jackfromperu

Reputation: 9

Can't send E-Mails with Python

I have this code as I am trying to send E-Mails using Python.

def Mail():
   import smtplib
   import textwrap
   SERVER = "localhost"

   FROM = "fromemail"
   TO = ["toemail"] 

   SUBJECT =(input('What is the subject of your E-Mail'))

   TEXT =(input('What do you want the E-Mail to say?'))

   message = textwrap.dedent("""\
   From: %s
   To: %s
   Subject: %s

   %s
   """ % (FROM, ", ".join(TO), SUBJECT, TEXT))

   server = smtplib.SMTP(SERVER)
   server.sendmail(FROM, TO, message)
   server.quit()

This is the error message I get.

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    Mail()
  File "E:\Coursework\EMail.py", line 26, in Mail
    server = smtplib.SMTP(SERVER)
  File "C:\Python33\python-3.3.5\lib\smtplib.py", line 241, in __init__
    (code, msg) = self.connect(host, port)
  File "C:\Python33\python-3.3.5\lib\smtplib.py", line 322, in connect
    (code, msg) = self.getreply()
  File "C:\Python33\python-3.3.5\lib\smtplib.py", line 375, in getreply
    raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

Upvotes: 1

Views: 1975

Answers (1)

Isaac Philip
Isaac Philip

Reputation: 565

The 'Connection unexpectedly closed' shows that the server is probably ON but unable to create a connection to smtplib.

You could check the status of the port 25 smtp service to verify that,

# netstat -an | grep -i :25 tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN

Then, check the status of the service occupying the port 25,

# netstat -plnt | grep -i :25 tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 30860/master

You probably will have the same, then just check the status of the master/postfix process,

# systemctl status postfix

If you get the error highlighted as,

fatal: cannot handle socket type AF_INET6 with "inet_protocols = ipv4"

then quickly go to the postfix configuration file at /etc/postfix/main.cf and check if you have this text and uncomment it,

inet_protocols = ipv4

Then restart postfix,

# systemctl restart postfix

then check status, hopefully you shouldn't get any errors. Then check if python is able to connect to the SMTP server!

$ python -c 'import smtplib; smtplib.SMTP("localhost");'

You shouldn't get any output which shows that python is able to connect to the SMTP server.

you can run your email sending script now!

Upvotes: 1

Related Questions