Question

I want to check that I can send email from my python program. Unfortunately it failed and it looks to me because SMTP server does not accept my call. I just need to check that my program correct and I could send email ... but I failed to check it. Here's my program and how could I make server to accept my call?

import smtplib

# Here are the email package modules we'll need
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

COMMASPACE = ', '

# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject'] = 'Our family reunion'
me = "susja@gmail.com"
family = "dusja@gmail.com"
msg['From'] = me
msg['To'] = COMMASPACE.join(family)
msg.preamble = 'Our family reunion'


# Send the email via our own SMTP server.
s = smtplib.SMTP('smtp.gmail.com')
s.sendmail(me, family, msg.as_string())
s.quit()

I've got this error:

Traceback (most recent call last):
File "2.py", line 21, in <module>
s = smtplib.SMTP('smtp.gmail.com')
File "/usr/lib/python2.7/smtplib.py", line 249, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python2.7/smtplib.py", line 309, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.7/smtplib.py", line 284, in _get_socket
return socket.create_connection((port, host), timeout)
File "/usr/lib/python2.7/socket.py", line 562, in create_connection
sock.connect(sa)
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
KeyboardInterrupt
Was it helpful?

Solution

Three things appear to be missing in the code sequence above:

  • you need to use port 587
  • a call to starttls() is needed to switch to the SSL/TLS protocol
  • you need to login to the Gmail SMTP server by calling login with your gmail username and password.

The last section of your code should now look like this:

s = smtplib.SMTP_SSL("smtp.gmail.com", 587)
s.starttls()
s.login('gmail_username', 'gmail_password')
s.sendmail(me, family, msg.as_string())
s.close()

OTHER TIPS

Just for anyone who runs into a similar problem with AWS and Flask, the solution I found was to set the environment variable MAIL_USE_TLS=True. Again this is only for flask.ext.mail, but it may save someone some time and effort in the future.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top