Python smtp.connect does not connect - python

I'm writing a small python script to send an email, but my code isn't even getting past smtp connection. I'm using the following code, but I never see "Connected". Additionally, I'm not seeing an exception thrown, so I think it's hanging on something.
import os
import platform
import smtplib
#Define our SMTP server. We use gmail. Try to connect.
try:
server = smtplib.SMTP()
print "Defined server"
server.connect("smtp.gmail.com",465)
print "Connected"
server.ehlo()
server.starttls()
server.ehlo()
print "Complete Initiation"
except Exception, R:
print R

Port 465 is for SMTPS; to connect to SMTPS you need to use the SMTP_SSL; however SMTPS is deprecated, and you should be using 587 (with starttls). (Also see this answer about SMTPS and MSA).
Either of these will work: 587 with starttls:
server = smtplib.SMTP()
print("Defined server")
server.connect("smtp.gmail.com",587)
print("Connected")
server.ehlo()
server.starttls()
server.ehlo()
or 465 with SMTP_SSL.
server = smtplib.SMTP_SSL()
print("Defined server")
server.connect("smtp.gmail.com", 465)
print("Connected")
server.ehlo()

Related

Unable to find solution for SMTP connection for Microsoft outlook

I am trying to connect to the SMTP server.
However, I am getting the error below:
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
import smtplib
conn = smtplib.SMTP('smtp-mail.outlook.com', 587)
You haven't really established a connection within your code. Try to do it like this:
import smtplib
email=input('Insert email: ')
password=input('Insert password: ')
server = smtplib.SMTP('smtp-mail.outlook.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(email, password)
Make sure the credentials are correct, otherwise it'll raise a 'smtplib.SMTPAuthenticationError'. Once you're done reading/sending/whatever else you have to do, don't forget to add server.close() to the script before terminating it.

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()

sending email from localhost works but fails when run on remote linux server

Following is a simple python script to send emails using gmail smtp server. This code works from my localhost in my windows machine but when i run the same code from a remote linux server, "socket.error: [Errno 97] Address family not supported by protocol" is thrown and the exception happens at this line " server = smtplib.SMTP('smtp.gmail.com:587')". I appreciate any help on what is causing this error. Thanks!
fromaddr = ''
toaddrs = ''
# Credentials (if needed)
username = ''
password = ''
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
msg = MIMEText('This is a test message')
server.sendmail(fromaddr, toaddrs, msg.as_string())
server.quit()

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