"Connection unexpectedly closed" error while sending email using SES from AWS - python-3.x

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

There seems to have some issue with port 465.Change the code to below and it will work fine.
MAIL['PORT'] = 587

Related

Unable to Send an email via python- Error- smtplib.SMTPServerDisconnected: Connection unexpectedly closed

port = 465 # For SSL
smtp_server = "smtp.mail.yahoo.com"
sender_email = "c.junction#yahoo.com" # Enter your address
password = input("Type your password and press enter:")
receiver_email = "jawoneb660#jobsfeel.com" # Enter receiver address
Subject = "Hi there"
message = """Hello World!!!
This message is sent from Python."""
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as smtp:
smtp.login(sender_email, password)
smtp.sendmail(sender_email, receiver_email, Subject, message)
I tried checking if there is any auth failure.Email could not be sent. I got following error msg.
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly
closed`
import smtplib ##Import needed modules
import ssl
port = 465 # For SSL
smtp_server = "smtp.mail.yahoo.com"
sender_email = "c.junction#yahoo.com" # Enter your address
password = input("Type your password and press enter:")
receiver_email = "jawoneb660#jobsfeel.com" # Receiver address
Subject = "Hi there"
message = """Hello World!!!
This message is sent from Python."""
context = ssl.create_default_context()
try:
print("Connecting to server...")
yahoo_server = smtplib.SMTP(smtp_server, port)
yahoo_server.starttls(context=context)
yahoo_server.login(sender_email, password)
print("Connected to server!")
print(f"Sending email to - {receiver_email}")
yahoo_server.sendmail(sender_email, receiver_email, Subject, message)
print("Email successfully sent to - {receiver_email}")
except Exception as e:
print(e)
finally:
yahoo_server.quit
I added a couple of modules that I didn't see. But you need those in order to use the ssl methods as well as the smtplib.
I also added a couple of print statements to help with seeing where in the process this might be getting hung up. You also want to close the connection as best practice.
lastly I added a variable to use with the steps of logging into the smtp server. I did this for Gmail recently so I don't know if this will work offhand, but at the very least the print statements and additional variables should hopefully help with that as well.

SMTP server with python3

I'm trying to send an email to my webmail(yahoo) using python3 but I have some problems with the object. I've tried with different ports(465/587) without any success:
import smtplib
pass='letmein'
sender = 'manolo#yahoo.es'
receivers = ['raul#yahoo.es']
message = """From: From Person <from#fromdomain.com>
To: To Person <to#todomain.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP_SSL('smtp.mail.yahoo.com', 465) ### 587)
smtpObj.set_debuglevel(1)
smtpObj.login(sender, pass)
smtpObj.sendmail(sender, receivers, message)
print("Successfully sent email")
except SMTPException:
print("Error: unable to send email")
And this is the error I get:
send: 'ehlo [192.168.0.15]\r\n'
reply: b'250-kubenode501.mail-prod1.omega.ir2.yahoo.com Hello [192.168.0.15] [81.61.24.111])\r\n'
reply: b'250-PIPELINING\r\n'
reply: b'250-ENHANCEDSTATUSCODES\r\n'
reply: b'250-8BITMIME\r\n'
reply: b'250-SIZE 41697280\r\n'
reply: b'250 AUTH PLAIN LOGIN XOAUTH2 OAUTHBEARER\r\n'
reply: retcode (250); Msg: b'kubenode501.mail-prod1.omega.ir2.yahoo.com Hello [192.168.0.15] [81.61.24.111])\nPIPELINING\nENHANCEDSTATUSCODES\n8BITMIME\nSIZE 41697280\nAUTH PLAIN LOGIN XOAUTH2 OAUTHBEARER'
send: 'AUTH PLAIN AGF1c3RyYWxiaXRAeWFob28uZXMAQWFsaWNpYTAy\r\n'
reply: b'535 5.7.0 (#AUTH005) Too many bad auth attempts.\r\n'
reply: retcode (535); Msg: b'5.7.0 (#AUTH005) Too many bad auth attempts.'
send: 'AUTH LOGIN YXVzdHJhbGJpdEB5YWhvby5lcw==\r\n'
Error: unable to send email
Any idea about how to fix this error?
There are a few things to fix:
Use smtplib.SMTP_SSL('smtp.mail.yahoo.com', 465) because port 465 expects connection using SSL.
Add smtpObj.set_debuglevel(1) to have better help with debugging - this will tell you that you need to login first.
Use smtpObj.login("login", "password") before trying to send an email.
The From email should be the same as the login.

SSL error while sending email using smtp with Python

I want to send an email using outlook. The code is as follows:
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg['From'] = '*******'
msg['Subject'] = 'Some subject here'
msg['To'] = '********'
msg.set_content('Some text here')
with smtplib.SMTP_SSL('smtp-mail.outlook.com', 587) as smtp:
smtp.login('******', '****')
smtp.send_message(msg)
print('Email sent!')
I get the following error:
---------------------------------------------------------------------------
SSLError Traceback (most recent call last)
<ipython-input-8-4d5956f55c88> in <module>
6 msg.set_content('Some text here')
7
----> 8 with smtplib.SMTP_SSL('smtp-mail.outlook.com', 587) as smtp:
9 smtp.login('sender_email', 'password')
10 smtp.send_message(msg)
~/anaconda/envs/quant2/lib/python3.6/smtplib.py in __init__(self, host, port, local_hostname, keyfile, certfile, timeout, source_address, context)
1029 self.context = context
1030 SMTP.__init__(self, host, port, local_hostname, timeout,
-> 1031 source_address)
1032
1033 def _get_socket(self, host, port, timeout):
~/anaconda/envs/quant2/lib/python3.6/smtplib.py in __init__(self, host, port, local_hostname, timeout, source_address)
249
250 if host:
--> 251 (code, msg) = self.connect(host, port)
252 if code != 220:
253 self.close()
~/anaconda/envs/quant2/lib/python3.6/smtplib.py in connect(self, host, port, source_address)
334 if self.debuglevel > 0:
335 self._print_debug('connect:', (host, port))
--> 336 self.sock = self._get_socket(host, port, self.timeout)
337 self.file = None
338 (code, msg) = self.getreply()
~/anaconda/envs/quant2/lib/python3.6/smtplib.py in _get_socket(self, host, port, timeout)
1037 self.source_address)
1038 new_socket = self.context.wrap_socket(new_socket,
-> 1039 server_hostname=self._host)
1040 return new_socket
1041
~/anaconda/envs/quant2/lib/python3.6/ssl.py in wrap_socket(self, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname, session)
405 suppress_ragged_eofs=suppress_ragged_eofs,
406 server_hostname=server_hostname,
--> 407 _context=self, _session=session)
408
409 def wrap_bio(self, incoming, outgoing, server_side=False,
~/anaconda/envs/quant2/lib/python3.6/ssl.py in __init__(self, sock, keyfile, certfile, server_side, cert_reqs, ssl_version, ca_certs, do_handshake_on_connect, family, type, proto, fileno, suppress_ragged_eofs, npn_protocols, ciphers, server_hostname, _context, _session)
815 # non-blocking
816 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
--> 817 self.do_handshake()
818
819 except (OSError, ValueError):
~/anaconda/envs/quant2/lib/python3.6/ssl.py in do_handshake(self, block)
1075 if timeout == 0.0 and block:
1076 self.settimeout(None)
-> 1077 self._sslobj.do_handshake()
1078 finally:
1079 self.settimeout(timeout)
~/anaconda/envs/quant2/lib/python3.6/ssl.py in do_handshake(self)
687 def do_handshake(self):
688 """Start the SSL/TLS handshake."""
--> 689 self._sslobj.do_handshake()
690 if self.context.check_hostname:
691 if not self.server_hostname:
SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:852)
Microsoft Outlook uses STARTTLS when sending an email. So you need to replace smtplib.SMTP_SSL with smtplib.SMTP and you need to call starttls
reference: smtplib.SMTP.starttls
import smtplib
from email.message import EmailMessage
sender = 'somename#outlook.com'
recipient = 'somename#gmail.com'
msg = EmailMessage()
msg.set_content('this is a test')
msg['From'] = 'somename#outlook.com'
msg['To'] = 'somename#gmail.com'
msg['Subject'] = 'test email'
with smtplib.SMTP('smtp.office365.com', 587) as server:
server.ehlo()
server.starttls()
server.ehlo()
server.ehlo()
server.login('your_login', "your_password", initial_response_ok=True)
server.ehlo()
server.sendmail(sender, recipient, msg.as_string())
print('Email sent!')
server.close()
Here is the Outlook message in my Gmail account.
I noted that I had to change my Outlook password, because it had a \n, which Python read as a new line.
----------------------------------------
My system information
----------------------------------------
Platform: macOS
OS Version: 10.15.7
Python Version: 3.9
----------------------------------------
Your question didn't identity the type of Outlook account you have.
Free account
Corporate account
You stated in the comments below that your error message included ask your email administrator. I haven't seem this message with the Free account so I'm assuming that you might have a Corporate account. If you do have the latter please review this Enable or disable authenticated client SMTP submission, because an email administrator would need to enable Authenticated SMTP on your corporate account.
The answer from user "Life is complex" is almost right. I would like to add few more things from myside which might help. I am not very sure which python version you are using here. I am guessing it as Python 3.X. You need to go through based on actual version of python you are using in your case.
From Python smtplib documents, link. Please check which python version you are using with below guide line.
class smtplib.SMTP_SSL(host='', port=0, local_hostname=None,
keyfile=None, certfile=None, [timeout, ]context=None,
source_address=None) An SMTP_SSL instance behaves exactly the same as
instances of SMTP. SMTP_SSL should be used for situations where SSL is
required from the beginning of the connection and using starttls() is
not appropriate. If host is not specified, the local host is used. If
port is zero, the standard SMTP-over-SSL port (465) is used. The
optional arguments local_hostname, timeout and source_address have the
same meaning as they do in the SMTP class. context, also optional, can
contain a SSLContext and allows configuring various aspects of the
secure connection. Please read Security considerations for best
practices.
keyfile and certfile are a legacy alternative to context, and can
point to a PEM formatted private key and certificate chain file for
the SSL connection.
Changed in version 3.3: context was added.
Changed in version 3.3: source_address argument was added.
Changed in version 3.4: The class now supports hostname check with
ssl.SSLContext.check_hostname and Server Name Indication (see
ssl.HAS_SNI).
Deprecated since version 3.6: keyfile and certfile are deprecated in
favor of context. Please use ssl.SSLContext.load_cert_chain() instead,
or let ssl.create_default_context() select the system’s trusted CA
certificates for you.
Changed in version 3.9: If the timeout parameter is set to be zero, it
will raise a ValueError to prevent the creation of a non-blocking
socket
You need to check that SSLV3 is enabled at Server end or not. Check out this link to see which client version can connect to which server version SSL Version Compatibility first.
import smtplib
import ssl
context = ssl.SSLContext(ssl.PROTOCOL_TLS)
#Above line is required to switch default SSLV3 protocol to TLS, recommended by python docs
# If you want to use SSLV3 and you are sure that it is enabled on server end then use
#context = ssl.SSLContext(ssl.PROTOCOL_SSLv3)
connection = smtplib.SMTP('smtp-mail.outlook.com', 587)
connection.ehlo()
connection.starttls(context=context)
connection.ehlo()
connection.login('now_your_real_login_data#outlook.com', 'otherwise_SMTPServerDisconnect')
The accepted answer didn't work for me, I kept getting this error:
smtplib.SMTPNotSupportedError: STARTTLS extension not supported by server.
I also tried SMTP_SSL instead of SMTP:
context = ssl.SSLContext(ssl.PROTOCOL_TLS)
with smtplib.SMTP_SSL('smtp-mail.outlook.com', 587, context=context) as server:
server.ehlo()
server.starttls(context=context)
but got this error:
[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1131)
Fortunately this post (thanks #dhruv-gami) helped me find my issue.
I found out that my hostname (using WSL on windows) is uppercase, but Outlook servers do not accept uppercase host names.
The solution is to just add a lowercase string in the ehlo commands:
with smtplib.SMTP('smtp.office365.com', 587) as server:
server.ehlo('lowercase')
server.starttls()
server.ehlo('lowercase')
server.login('your_login', "your_password", initial_response_ok=True)

O365 smtp as relay implementation

I am using the below lines of code to send an email but I get the error as 'smtplib.SMTPAuthenticationError: (535, b'5.7.3 Authentication unsuccessful' . This must be due to MFA. what can I do to authenticate?
import smtplib, ssl
port = 587 # For starttls
smtp_server = "smtp.office365.com"
sender_email = "myemail#companycom"
receiver_email = "myemail#companycom"
password = input("Type your password and press enter:")
message = """\
Subject: Hi there
This message is sent from Python."""
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
server.ehlo() # Can be omitted
server.starttls(context=context)
server.ehlo() # Can be omitted
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
The solution to this issue is to manage the app password in your account or request for service accounts to your admin which doesn't have MFA.

Getting timedout during smtplib.SMTP(“smtp.gmail.com”, 587) in Python

The following code is working perfectly in another computer:
def send_email(user, pwd, recipient, subject, body):
#lb.send_email('AlirezaFedEx#gmail.com','P&ENLAMS','info#nka-it.com','Test','This is a test')
import smtplib
FROM = 'AlXXX#gmail.com'
TO = ['info#XXX.com'] # recipient if isinstance(recipient, list) else [recipient]
SUBJECT = 'Test'#subject
TEXT = 'This is a test' #body
# Prepare actual message
message = """From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
server = smtplib.SMTP('smtp.gmail.com',587)
server.ehlo()
server.starttls()
server.login(user, pwd)
server.sendmail(FROM, TO, message)
server.close()
print('successfully sent the mail')
except Exception as err:
print("failed to send mail:" + str(err))
When running the following part:
server = smtplib.SMTP('smtp.gmail.com',587)
it starts to freeze and eventually gives the following error:
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
I checked proxy of my browser and disabled proxy but still getting the error. Any advice please?
are you using proxy? If so, please disable the proxy and try again. This should work properly if you have an active internet connection.

Resources