title: How can I send email using Python?
body: <p>I am writing a program that sends  an email using Python. What I have learned from various forums is the following piece of code:</p>
  
  <pre><code>#!/usr/bin/env python
  import smtplib
  sender = "sachinites@gmail.com"
  receivers = ["abhisheks@cse.iitb.ac.in"]
  yourname = "Abhishek Sagar"
  recvname = "receptionist"
  sub = "Testing email"
  body = "who cares"
  message = "From: " + yourname + "\n" 
  message = message + "To: " + recvname + "\n"
  message = message + "Subject: " + sub + "\n" 
  message = message + body
  try:
      print "Sending email to " + recvname + "...",
      server = smtplib.SMTP('smtp.gmail.com:587')
      username = 'XYZ@gmail.com'  
      password = '*****'  
      server.ehlo()
      server.starttls()  
      server.login(username,password)  
      server.sendmail(sender, receivers, message)         
      server.quit()
      print "successfully sent!"
  except  Exception:
      print "Error: unable to send email"
  </code></pre>
  
  <p>But it is simply printing ""Error: unable to send email" and exits out on the terminal. How might I resolve this?</p>
  
  <p>I modified the last two lines to <br></p>
  
  <pre><code>except Exception, error:
      print "Unable to send e-mail: '%s'." % str(error)
  </code></pre>
  
  <p>I get the following error message :</p>
  
  <pre><code>Traceback (most recent call last):
    File "./2.py", line 45, in &lt;module&gt;
      smtpObj = smtplib.SMTP('localhost')
    File "/usr/lib/python2.6/smtplib.py", line 239, in __init__
      (code, msg) = self.connect(host, port)
    File "/usr/lib/python2.6/smtplib.py", line 295, in connect
      self.sock = self._get_socket(host, port, self.timeout)
    File "/usr/lib/python2.6/smtplib.py", line 273, in _get_socket
      return socket.create_connection((port, host), timeout)
    File "/usr/lib/python2.6/socket.py", line 514, in create_connection
      raise error, msg
  socket.error: [Errno 111] Connection refused
  </code></pre>