"Connection unexpectedly closed" error while sending email using SES from AWS

Viewed 867

So I'm trying to send an email to my self using SMTP and AWS. The email I'm using on my configuration is verified since I'm still using sandbox mode in SES. While running the script I keep getting the error Connection unexpectedly closed even dough I tried to connect with OpenSSL and it connected but it showed a Didn't find STARTTLS in server response, trying anyway... error after connecting.

Here is my code:

MAIL = {}
MAIL['USERNAME'] = 'AKIAXARHTFGFKCDAO7PD'
MAIL['PASSWORD'] = 'BE0tXPq8wteiKZYtgD2TgtfFTGhgFGOhUp3F0lG0uqn'
MAIL['HOST'] = 'email-smtp.eu-central-1.amazonaws.com'
MAIL['PORT'] = 465


# Set user code
            code = random.randrange(000000, 999999)
            # Send email to user
            print(code)
            print(current_user.email)
            msg = MIMEMultipart('alternative')
            msg['Subject'] = 'Ruby - Verification code'
            msg['From'] = 'amng835@gmail.com'
            msg['To'] = current_user.email
            msg.attach(MIMEText(f'Your verification code is: {code}', 'plain'))
            try:
                server = smtplib.SMTP(MAIL['HOST'], MAIL['PORT'])
                server.ehlo()
                server.starttls()
                server.ehlo()
                server.login(MAIL('MAIL_USERNAME'), MAIL('MAIL_PASSWORD'))
                server.sendmail('amng835@gmail.com', current_user.email, msg.as_string())
                server.close()
            except Exception as error:
                print('Failed to send message to user')
                print(error)

OpenSSL output:

The command:

openssl s_client -connect email-smtp.eu-central-1.amazonaws.com:465 -starttls smtp

The output:

CONNECTED(00000005)
Didn't find STARTTLS in server response, trying anyway...
write:errno=0
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 372 bytes
Verification: OK
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
Early data was not sent
Verify return code: 0 (ok)
---

My documentation source: https://docs.aws.amazon.com/ses/latest/DeveloperGuide/examples-send-using-smtp.html

1 Answers

There seems to have some issue with port 465.Change the code to below and it will work fine.

MAIL['PORT'] = 587
Related