Search code examples
pythonpython-3.xemailsmtplib

Error in Email Program in Python


I started with a very simple email program in python where I am trying to send an message from my GMail address. I am always getting the error below,

Traceback (most recent call last):
  File "C:\Users\BarmanJa\Documents\PythonfromShell\TT\infi.py", line 15, in <module>
    server = smtplib.SMTP('smtp.gmail.com', 587)
  File "C:\Users\BarmanJa\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 251, in __init__
    (code, msg) = self.connect(host, port)
  File "C:\Users\BarmanJa\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 336, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "C:\Users\BarmanJa\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 307, in _get_socket
    self.source_address)
  File "C:\Users\BarmanJa\AppData\Local\Programs\Python\Python36-32\lib\socket.py", line 724, in create_connection
    raise err
  File "C:\Users\BarmanJa\AppData\Local\Programs\Python\Python36-32\lib\socket.py", line 713, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

I have tried all possible ways to correct it. I went through all the similar problems others had posted in the community but no change. Below is the original code

import smtplib

mailfrom = 'jayantamgr@gmail.com'
msg = 'Hello'

mailto = ('myname@yahoo.com')
username = 'hisname@gmail.com'
password = 'wwwwwwwwww'
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
s.starttls()
server.login(username, password)

server.sendmail(mailfrom, mailto , msg)
server.quit()

Solution

  • The error message indicates that you can’t connect to the target machine (smtp.gmail.com):

    ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

    I would suspect that you have some sort of firewall or anti-virus that blocks connections to the SMTP Submission Port as both the specified hostname (smtp.gmail.com) and port number are correct (587).


    There’s also an (unrelated) error in your code: s.starttls() should be server.starttls().