new to, previously i am sending emails using smtplib from python. it was running fine when i am on my local python env. i tested python 2 and 3 both. after i joined i switched same code here. now issue is script was running fine when i am in python2 but in python3 i faces this issue. i guess python version is not an problem. some sort of certification issue that i don't have knowledge about. here is the Traceback.

  Traceback (most recent call last):
  File "", line 20, in <module>
  File "/usr/lib/python3.6/", line 770, in starttls
  File "/usr/lib/python3.6/", line 401, in wrap_socket
    _context=self, _session=session)
  File "/usr/lib/python3.6/", line 808, in __init__
  File "/usr/lib/python3.6/", line 1061, in do_handshake
  File "/usr/lib/python3.6/", line 683, in do_handshake
ssl.SSLError: [SSL: TLSV1_UNRECOGNIZED_NAME] tlsv1 unrecognized name (_ssl.c:749)

When you connect to a secure SMTP server, just as when you access a site over HTTPS, the server sends back a certificate to prove that it is the server it claims to be. I believe that error is saying that the server is sending back the wrong certificate. Python 2.7.6 (which is currently our point release for 2.7 -- that's changing soon) has different TLS libraries to Python 3.x, so that might explain the difference.

Is the server that you're trying to connect to one that you have set up yourself? Or is it provided by a third party?

no i have't set up any server just using smtp library for sending mail here is the code that i am using and code working fine for python2 and 3 both on local env.

strFrom = ['']
strTo = ['']
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'test message'

fp = open('img', 'rb')
img = MIMEImage(
img.add_header('Content-ID', '<image1>')

smtp = smtplib.SMTP()
smtp.login('', 'password')
smtp.sendmail(strFrom, strTo, msgRoot.as_string())

if the code is working fine locally, I would definitely double check what python 3 versions you are using locally vs on PythonAnywhere.

Also- how are you running the python code on PythonAnywhere? ie. an interactive console, or is this part of webapp code, or something else.

also saw something suggesting you should put the server in smtp = smtplib.SMTP() and skip the smtp.connect step. ie. SMTP() already automatically does the connect.

thank you for suggestions. so in local disk it works fine with Python 3.5.2 . and in PythonAnywhere it is failed with python3.5 so it is python 3.5 i guess. i also tried with Python 3.6.0 in pythonanywhere and still i won't works. i am running this script from regular bash console .

Maybe try changing it as Conrad suggests so that instead of

smtp = smtplib.SMTP()
smtp.starttls() have

smtp = smtplib.SMTP(host="", port=587)

This Stack Overflow post suggests that it might help and make it work both locally and on PythonAnywhere.

And boom. this solution works for me. thank you. @giles , @conrad

Hooray! Thanks for confirming :-)