8

I am writing a program that sends an email using Python. What I have learned from various forums is the following piece of 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"

But it is simply printing ""Error: unable to send email" and exits out on the terminal. How might I resolve this?

I modified the last two lines to

except Exception, error:
    print "Unable to send e-mail: '%s'." % str(error)

I get the following error message :

Traceback (most recent call last):
  File "./2.py", line 45, in <module>
    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
salmanwahed
  • 9,450
  • 7
  • 32
  • 55
Abhishek Sagar
  • 1,189
  • 4
  • 20
  • 44
  • I see you're new to stackoverflow, welcome! Make sure you use the [editing help](http://stackoverflow.com/editing-help) to properly format your posts. This helps us read your question more easily and increases your chances of getting an answer. – André Caron Feb 14 '12 at 05:43
  • 1
    possible duplicate of [Sending mail from Python using SMTP](http://stackoverflow.com/questions/64505/sending-mail-from-python-using-smtp) – Eli Bendersky Feb 14 '12 at 06:00

3 Answers3

16

If message headers, payload contain non-ascii characters then they should be encoded:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from email.header    import Header
from email.mime.text import MIMEText
from getpass         import getpass
from smtplib         import SMTP_SSL


login, password = 'user@gmail.com', getpass('Gmail password:')
recipients = [login]

# create message
msg = MIMEText('message body…', 'plain', 'utf-8')
msg['Subject'] = Header('subject…', 'utf-8')
msg['From'] = login
msg['To'] = ", ".join(recipients)

# send it via gmail
s = SMTP_SSL('smtp.gmail.com', 465, timeout=10)
s.set_debuglevel(1)
try:
    s.login(login, password)
    s.sendmail(msg['From'], recipients, msg.as_string())
finally:
    s.quit()
jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • Gmail is now pretty tight with what devices can sign in to the account. If, like me, you have issues using code like this on a remote machine you can try logging into gmail account and checking the "Allow less secure apps" option. There are also tools to authorize specific apps – jprockbelly Dec 07 '15 at 11:11
  • 1
    @jprockbelly: don't compromise security. It works even on the account with 2-step verification. Just generate an app password for your script. – jfs Dec 07 '15 at 11:35
6

If you print the error message, you will likely get a comprehensive description of what error occurred. Try (no pun intended) this:

try:
    # ...
except Exception, error:
    print "Unable to send e-mail: '%s'." % str(error)

If, after reading the error message, you still do not understand your error, please update your question with the error message and we can help you some more.


Update after additional information:

the error message

socket.error: [Errno 111] Connection refused

means the remote end (e.g. the GMail SMTP server) is refusing the network connection. If you take a look at the smtplib.SMTP constructor, it seems you should change

server = smtplib.SMTP('smtp.gmail.com:587')

to the following.

server = smtplib.SMTP(host='smtp.gmail.com', port=587)
André Caron
  • 44,541
  • 12
  • 67
  • 125
  • after doing what you said , i get the following error : Sending email to receptionist... Unable to send e-mail: '[Errno 110] Connection timed out' . i am behind the proxy , so do i need to add something extra to the code. – Abhishek Sagar Feb 14 '12 at 06:22
  • @AbhishekSagar: SMTP configuration is a complex topic. Perhaps you can try one of the alternate ports? See [configuring other email clients](http://support.google.com/mail/bin/answer.py?hl=en&answer=13287) in the GMail frequently asked questions. – André Caron Feb 14 '12 at 06:55
  • yes, i install postfix , and gave up the idea when i searched Configuring the SMTP ! its really complex. – Abhishek Sagar Feb 14 '12 at 07:36
0

According to the error message, you use the localhost as the SMTP server, then the connection was refused. Your localhost didn't have an SMTP sever running I guess, you need to make sure the SMTP server you connect is valid.

Will Cheng
  • 199
  • 1
  • 7