Send e-mail with python error "Connection unexpectedly closed" - python

I want to send a E-mail using python using this code but the final result is a "Connection unexpectedly closed" error:
import smtplib
sender_email = "example#gmail.com"
rec_email = "example2#gmail.com"
password = "password"
message = "Test message using python !"
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, password)
server.sendmail(sender_email, rec_email, message)
This is the error:
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

It might be that the bigger email providers (I would believe this includes Gmail) block 'unsafe applications' from accessing the server.
You might want to try to login to sender_email and there should be an option somewhere that allows 'unsafe applications to access', or something similar.
I had a similar problem when doing the same thing with my Yahoo account, and this basically solved the problem.

Related

Python smtplib second connection failing

I am trying to connect to my mail server, then disconnect, then reconnect at another time. The initial connection works and the email is sent. I disconnect using quit() and the reply is closing the connection. When I attempt to connect again, it raises SMTPServerDisconnected please run connect() first. I found this from a few years ago as the exact same problem (https://bugs.python.org/issue22216) and it shows that it was fixed. I am having this same issue now and unsure how to properly fix it or close the connection.
mail = smtplib.SMTP_SSL('mail.hostname.com', 465)
MAIL_PASS = 'password'
SENDER = 'name#hostname.com'
RECEIVER = 'receiver#something.com'
while True:
if (something)
mail.login(SENDER, MAIL_PASS)
mail.sendmail(SENDER, RECEIVER, 'test email')
mail.quit()
elif (something else)
mail.login(SENDER, MAIL_PASS)
mail.sendmail(SENDER, RECEIVER, 'test2 email')
mail.quit()
After the first email and the quit request it says this:
reply: b'221 box5454.bluehost.com closing connection\r\n'
reply: retcode (221); Msg: b'box5454.bluehost.com closing connection'
The next connection attempt says this:
send: 'ehlo [127.0.1.1]\r\n'
Traceback (most recent call last):
mail.login(SENDER, MAIL_PASS)
self.ehlo_or_helo_if_needed()
if not (200 <= self.ehlo()[0] <= 299):
self.putcmd(self.ehlo_msg, name or self.local_hostname)
self.send(str)
raise SMTPServerDisconnected('please run connect() first')
smtplib.SMTPServerDisconnected: please run connect() first
I have found a way to make the program work. I am using a while True to continue the program. It seems when I declare the variable for the smtplib before while True, it has the problem. I declare the variable after while True and it works. May be a noob problem using while True, but it drove me nuts and hopefully it will help someone else
MAIL_PASS = 'password'
SENDER = 'name#hostname.com'
RECEIVER = 'receiver#something.com'
while True:
mail = smtplib.SMTP_SSL('mail.hostname.com', 465)
if (something)
mail.login(SENDER, MAIL_PASS)
mail.sendmail(SENDER, RECEIVER, 'test email')
mail.quit()
elif (something else)
mail.login(SENDER, MAIL_PASS)
mail.sendmail(SENDER, RECEIVER, 'test2 email')
mail.quit()

Using smtplib to send an email to mailtrap only works when code is not within function or class

this question is somehow similar to python: sending a mail, fails when inside a "with" block .
I'm using Python (3.6) to send emails to mailtrap smtp. Mailtrap actually provides you with the integration code for smtplib which is the one below:
import smtplib
sender = "Private Person <from#smtp.mailtrap.io>"
receiver = "A Test User <to#smtp.mailtrap.io>"
message = f"""\
Subject: Hi Mailtrap
To: {receiver}
From: {sender}
This is a test e-mail message."""
with smtplib.SMTP("smtp.mailtrap.io", 2525) as server:
server.login("<MYUSER>", "<MYPASSWORD>")
server.sendmail(sender, receiver, message)
The code above works just fine if I place it in a module and run it.I go to mailtrap inbox and verify that the email is there. However I want to encapsulate this in a function like this:
import smtplib
from socket import gaierror
def test():
sender = "Test Dev <from#smtp.mailtrap.io>"
receiver = "Test User <to#smtp.mailtrap.io>"
message = f"""\
Subject: Hi there
To: {receiver}
From: {sender}
TESTING"""
try:
with smtplib.SMTP("smtp.mailtrap.io", 2525) as server:
server.login("<MYUSER>", "<MYPASSWORD")
print("Sending email")
server.sendmail(sender, receiver, message)
print('Sent')
except (gaierror, ConnectionRefusedError):
print('Failed to connect to the server. Bad connection settings?')
except smtplib.SMTPServerDisconnected:
print('Failed to connect to the server. Wrong user/password?')
except smtplib.SMTPException as e:
print('SMTP error occurred: ' + str(e))
if __name__ == "__main__":
test()
This doesn't work. WHY? Here is the output:
output image
There's no connection error or any other exception. However I go to mailtrap and don't find the email there.
Is this a mailtrap issue or is it related to smtplib ? I'm cracking my head around this one
I was having this same issue and couldn't wrap my head around it. I did notice that when I made my message an empty string, it worked.
After an embarrassingly long time of searching; I found this post which pointed me to the solution.
You must set the MIME type of the email message. So rather than just passing a string you pass a message object:
message = MIMEText("TEST!")
message["Subject"] = "Alert!"
message["From"] = sender
message["To"] = receiver
... then eventually
server.sendmail(sender, receiver, message.as_string())
my full send email function looks like this:
def send_mail(self):
message = MIMEText("TEST!")
message["Subject"] = "Alert!"
message["From"] = sender
message["To"] = receiver
try:
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
server.set_debuglevel(1)
server.ehlo() # Can be omitted
server.starttls(context=context)
server.ehlo() # Can be omitted
server.login(login, password)
server.sendmail(sender, receiver, message.as_string())
print('Sent')
except (gaierror, ConnectionRefusedError):
print('Failed to connect to the server. Bad connection settings?')
except smtplib.SMTPServerDisconnected:
print('Failed to connect to the server. Wrong user/password?')
except smtplib.SMTPException as e:
print('SMTP error occurred: ' + str(e))
except Exception as e:
print('everything else')
It's unfortunate that you must specify the sender and receiver in both the message object and sendemail fuction.

Python freezes on smtplib.SMTP("smtp.gmail.com", 587)

I am attempting to create a script that send an email, using Gmail. However, my code freezes when the line below is ran:
smtplib.SMTP("smtp.gmail.com", 587)
It is before my username and password are entered, so it is nothing to do with my Gmail account. Why is this happening? I am using Python 3.6.3
The full code is below:
import smtplib
# Specifying the from and to addresses
fromaddr = 'XXX#gmail.com'
toaddrs = 'YYY#gmail.com'
# Writing the message (this message will appear in the email)
msg = 'Enter you message here'
# Gmail Login
username = 'XXX#gmail.com'
password = 'PPP'
# Sending the mail
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
It is most likely a firewall or similar issue. On the machine having the issue, try running this on the command line:
ping smtp.gmail.com
Assuming that works, then try:
telnet smtp.gmail.com 587
I'm assuming a Linux machine with this command. You'll need to adapt for others. If that connects, type ehlo list and the command should show some info. Type quit to exit.
If that doesn't work, then check your iptables.
sudo iptables -L
This will either show something like ACCEPT all under Chain INPUT or if not, you'll need to ensure that you are accepting established connections with something like:
ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED
The output chain is often open, but you should check that too.
If you are on AWS, check your security group isn't blocking outgoing connections.
If it's hanging in the call to smtplib.SMTP, and the server requires SSL, then most likely the issue is that you need to call smtplib.SMTP_SSL() (note the _SSL) instead of calling smtplib.SMTP() with a subsequent call to server.starttls() after the ehlo. See SMTPLib docs for SMTP_SSL for more details.
This fixed the issue for me.
Use server.ehlo() in your code.
Code Snippet:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
For authentication error:
http://joequery.me/guides/python-smtp-authenticationerror/
Add following code snippet and run again.
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.close()
print 'successfully sent the mail'
except:
print "failed to send mail"
You don't need the ehlo call. These days, you do need an app password with Gmail. And crucially, you need the right server address. I stupidly copied smtp.google.com from some bad instructions, and the call hung. Changing to smtp.gmail.com fixed it. Duh.

Smtplib: Connection unexpectedly closed

I am using following code:
def mailme():
print('connecting')
server = smtplib.SMTP('mail.server.com', 26)
server.connect("mail.server.com", 465)
print('connected..')
server.ehlo()
server.starttls()
server.ehlo()
server.login('scraper#server.com', "pwd")
text = 'TEST 123'
server.sendmail('me#sserver.com', 'me#server2.com', text)
server.quit()
but it gives error:
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
When connect via Telnet it works:
~ telnet mail.zoo00ooz.com 26
Trying 1.2.3.4...
Connected to server.com.
Escape character is '^]'.
220-sh97.surpasshosting.com ESMTP Exim 4.87 #1 Mon, 01 Jan 2018 00:23:02 -0500
220-We do not authorize the use of this system to transport unsolicited,
220 and/or bulk e-mail.
^C^C
I have attached the sample mailing code using Python 3.6.0 below
import smtplib as sl
server = sl.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login('sender_mail_id#gmail.com','sender_password')
server.sendmail('sender_mail_id#gmail.com',['first_receiver_mail_id#gmail.com','second_receiver_mail_id#gmail.com','and_so_on#gmail.com'],'data')
You don't need to connect twice !
As the documentation says:
exception smtplib.SMTPServerDisconnected¶
This exception is raised when the server unexpectedly disconnects, or when an attempt is made to use the SMTP instance before connecting it to a server.
Your code should be more something like this (even like this its somewhat over complicated, see documentation for a sample code)
def mailme():
SERVER_NAME='mail.whatever.com'
SERVER_PORT=25
USER_NAME='user'
PASSWORD='password'
print('connecting')
server = smtplib.SMTP(SERVER_NAME, SERVER_PORT)
print('connected..')
server.ehlo()
server.starttls()
server.ehlo()
server.login(USER_NAME, PASSWORD)
text = 'TEST 123'
server.sendmail('whoever#whatever.com', 'another#hatever.com', text)
server.quit()
mailme()

STARTTLS extension not supported by server

This maybe a repeated question but I'm still facing issues on this, hope there's a solution around. Thanks in advance.
I'm trying to send mail through the company's server
I'm currently using Python version 2.6 and Ubuntu 10.04
This is the error message I got
Traceback (most recent call last):
File "hxmass-mail-edit.py", line 227, in <module>
server.starttls()
File "/usr/lib/python2.6/smtplib.py", line 611, in starttls
raise SMTPException("STARTTLS extension not supported by server.") smtplib.SMTPException: STARTTLS extension not supported by server.
Here goes part of the code
server = smtplib.SMTP('smtp.abc.com', 587)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.ehlo()
server.login('sales#abc.com', 'abc123')
addressbook=sys.argv[1]
Remove the ehlo() before starttls().
starttls() + ehlo() results in two HELLO messages, which cause the server remove the STARTTLS in the reply message.
server = smtplib.SMTP('smtp.abc.com', 587)
server.starttls()
server.ehlo()
server.login('sales#abc.com', 'abc123')
I had a similar issue trying to send a mail through the company's server (without autentication needed)
I solved removing the server.ehlo and removing the port number:
server = smtplib.SMTP("smtp.mycompany.com")
server.sendmail(fromaddr, toaddr, text)
removing server.ehlo() before server.starttls() helped me get my code working! Thank you, Leonard!
my code:
s = smtplib.SMTP("smtp.gmail.com",587)
s.starttls()
s.ehlo
try:
s.login(gmail_user, gmail_psw)
except SMTPAuthenticationError:
print 'SMTPAuthenticationError'
s.sendmail(gmail_user, to, msg.as_string())
s.quit()
The error says it all, it seems the SMTP server sou are using doesn't support STARTTLS and you aru issuing server.starttls(). Try using the server without calling server.starttls().
Without more info is the only I can say.
I am able to resolve the issue with below code, by adding port number with server name:
server = smtplib.SMTP('smtp.abc.com:587')
from smtplib import SMTP_SSL, SMTP, SMTPAuthenticationError
from ssl import create_default_context
from email.message import EmailMessage
sender = 'aaa#bbb.com'
description = "This is the test description supposed to be in body of the email."
msg = EmailMessage()
msg.set_content(description)
msg['Subject'] = 'This is a test title'
msg['From'] = f"Python SMTP <{sender}>"
msg['To'] = 'bbb#ccc.com'
def using_ssl():
try:
server = SMTP_SSL(host='smtp.gmail.com', port=465, context=create_default_context())
server.login(sender, password)
server.send_message(msg=msg)
server.quit()
server.close()
except SMTPAuthenticationError:
print('Login Failed')
def using_tls():
try:
server = SMTP(host='smtp.gmail.com', port=587)
server.starttls(context=create_default_context())
server.ehlo()
server.login(sender, password)
server.send_message(msg=msg)
server.quit()
server.close()
except SMTPAuthenticationError:
print('Login Failed')
By testing and researching myself, I found out that the gmail servers do not use tls connections with python anymore.
You must not use service.startttls(). Gmail service do not support this type of connection anymore.
Also remember to use the SMTP ports (mail reserved ports) for sending emails.
POP3 and IMAP ports for receiving email.
s_u = "Test"
service = smtplib.SMTP_SSL("smtp.gmail.com", 465)
service.ehlo()
service.sendmail("SENDER_EMAIL","RECEIVER_EMAIL","MESSAGE")
You can't send the email even if you put the correct credentials,
look at this: Login credentials not working with Gmail SMTP
Are you sure that you want to encrypt (StartTLS) the connection to the mail server? I would contact someone who knows the insides of that server to see what protocol/encryption to use.
You say that upon removing the call to server.starttls(), you get a different series of error messages. Could you please post those messages as well?
Also, you might want to read up on StartTLS so you understand what it is and why you would want to use it. It seems you're writing a Serious Business program, in which case you'll probably want to understand what you are doing, security-wise.
Yes putting server.starttls() above server.ehlo() solved this.

Categories

Resources