How to send an email in python?
Question: I would like to send an email in Python. Below an example code:

    
    
    #!/usr/bin/python
    
    import smtplib
    
    sender = 'test@gmail.com'
    receivers = ['test@gmail.com']
    
    message = """From: From Person <from@fromdomain.com>
    To: To Person <to@todomain.com>
    Subject: SMTP e-mail test
    
    This is a test e-mail message.
    """
    
    try:
       smtpObj = smtplib.SMTP('localhost')
       smtpObj.sendmail(sender, receivers, message)         
       print("Send OK.")
    except SMTPException:
       print("Send NOT OK.")
    

When I try to run this program I got some errors:

    
    
    Traceback (most recent call last):
      File ".\sendEmail.py", line 16, in <module>
        smtpObj = smtplib.SMTP('localhost')
      File "C:\Python34\lib\smtplib.py", line 242,
        (code, msg) = self.connect(host, port)
      File "C:\Python34\lib\smtplib.py", line 321,
        self.sock = self._get_socket(host, port, se
      File "C:\Python34\lib\smtplib.py", line 292,
        self.source_address)
      File "C:\Python34\lib\socket.py", line 509, i
        raise err
      File "C:\Python34\lib\socket.py", line 500, i
        sock.connect(sa)
    ConnectionRefusedError: [WinError 10061] Nie mo
    
    During handling of the above exception, another
    
    Traceback (most recent call last):
      File ".\sendEmail.py", line 19, in <module>
        except SMTPException:
    NameError: name 'SMTPException' is not defined
    

How can I improve this code to send an email? Thanks.


Answer: Look at this line:

`smtpObj = smtplib.SMTP('localhost')`

You're trying to connect to localhost - your own computer. Do you have running
SMTP server? I don't think so.

Configure proper SMTP server. You can use your personal e-mail account for
that.

