Search code examples
pythonsmtp

Sending email from Python throwing SSLError 'unknown protocol'


I was sending emails from flask-mail but since trying to use the mailservers at namecheap or bluehost, I'm getting the following error:

SSLError: [Errno 1] _ssl.c:510: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol

So now I'm trying to send the email without flask-mail but I'm still getting the same error. Any fix? My code is as follows:

from smtplib import SMTP
smtp = SMTP()

smtp.set_debuglevel(debuglevel)
smtp.connect('xxxxxx', 26)
smtp.login('noreply@xxx.com', 'xxxxxxx')

from_addr = "xxx <noreply@xxx.com>"
to_addr = rec@xxx.com

subj = "hello"
date = datetime.datetime.now.strftime( "%d/%m/%Y %H:%M" )

message_text = "Hello\nThis is a mail from your server\n\nBye\n"

msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, message_text )

smtp.sendmail(from_addr, to_addr, msg)
smtp.quit()

My application is running on Ubuntu 14.04 on Amazon EC2.

Thanks.


Solution

  • The reason that this is giving you this error is because your mail server is not a SMTP server. Use Gmail or another smtp mail service to send the mail. Try sending it through a gmail account with the server being smtp.gmail.com and the port being 587. First though you will need to configure your account for it.