TimeoutError when using python to send email - python

I'm trying to write a python script to send an email. And here is the code:
def main():
import smtplib
import email.mime.text
import email.mime.application
from email.mime.multipart import MIMEMultipart
from_email = 'xxx#gmail.com'
from_email_pwd = '123456'
to_email = 'yyy#gmail.com'
msg = MIMEMultipart()
msg['Subject'] = 'Subject'
msg['From'] = from_email
msg['To'] = to_email
body = email.mime.text.MIMEText("Body")
msg.attach(body)
s = smtplib.SMTP('smtp.gmail.com')
s.starttls()
s.login(from_email, from_email_pwd)
s.sendmail(from_email, to_email, msg.as_string())
s.quit()
return
main()
While I can successfully run this code on my personal laptop, I came across problems when I try to run it on the company's desktop (working on PyCharm IDE with interpreter Python 3.5.1). Here is the error message:
Traceback (most recent call last):
File "C:/PATH/stack.py", line 29, in <module>
main()
File "C:/PATH/stack.py", line 21, in main
s = smtplib.SMTP('smtp.gmail.com')
File "C:\Username\AppData\Local\Programs\Python\Python35-32\lib\smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "C:\Username\AppData\Local\Programs\Python\Python35-32\lib\smtplib.py", line 335, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Username\AppData\Local\Programs\Python\Python35-32\lib\smtplib.py", line 306, in _get_socket
self.source_address)
File "C:\Username\AppData\Local\Programs\Python\Python35-32\lib\socket.py", line 711, in create_connection
raise err
File "C:\Username\AppData\Local\Programs\Python\Python35-32\lib\socket.py", line 702, in create_connection
sock.connect(sa)
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
Process finished with exit code 1
Any thoughts what's going on?

Related

Python Smtplib WinError 100022

I'm trying to send an email using Python and I used the material I found on the official site (https://docs.python.org/3/library/email.examples.html) but I'm getting an error when sending an email. Using the port and server works when I use Java but when using the same details in Python the code doesn't work.
The code that I am testing:
import smtplib
from email.message import EmailMessage
port = 25
server = "172.xxx.xxx.xxx"
from_add = "test#fakemail.com"
to_add = "test#fakemail.com"
message = "This is a test Email"
subject = "Test Email"
msg = EmailMessage()
msg.set_content(message)
msg["Subject"] = subject
msg["From"] = from_add
msg["To"] = to_add
#Send the message via our own SMTP server
s = smtplib.SMTP(server)
s.send_message(msg)
s.quit()
When I run my code I get the below error. I have been searching the net and all I am finding are errors concerning sockets (I tried adding which I haven't seen in any examples. My firewall admin tells me he doesn't see any traffic being blocked his end. Does anyone know if what I am coding is wrong?
Original
Traceback (most recent call last):
File "X:/test/test_email.py", line 21, in <module>
s = smtplib.SMTP(server)
File "X:\Enviroments_For_Python\PROD\lib\smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "X:\Enviroments_For_Python\PROD\lib\smtplib.py", line 336, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "X:\Enviroments_For_Python\PROD\lib\smtplib.py", line 307, in _get_socket
self.source_address)
File "X:\Enviroments_For_Python\PROD\lib\socket.py", line 728, in create_connection
raise err
File "X:\Enviroments_For_Python\PROD\lib\socket.py", line 711, in create_connection
sock = socket(af, socktype, proto)
File "X:\Enviroments_For_Python\PROD\lib\socket.py", line 151, in __init__
_socket.socket.__init__(self, family, type, proto, fileno)
OSError: [WinError 10022] An invalid argument was supplied
Process finished with exit code 1
Socket change (didn't work)
s.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sock.bind(server, port)
I found the problem. I am using Anaconda and had created a different environment. When I switched to the root environment my code worked without a problem.

Smtplib code working in python3.7 for linux but not for windows 10

I am trying to send automated mail through outlook using python3.7.The smtlib code is working fine for python installed in linux while the same code is returning me error for windows.
import time, os, smtplib
from datetime import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
print("sam")
s = smtplib.SMTP('smtp-mail.outlook.com', 587)
print("sam1")
s.starttls()
print("sam2")
s.login("samgupta#xyz.com", "Welcome")
message = "Hi"
print("sam3")
s.sendmail("samgupta#xyz.com", "abc#xyz.com", message)
s.quit()
This is the error message i am getting in windows python :
Traceback (most recent call last): File
"C:/Users/sysadmin/Desktop/mail.py", line 10, in
s = smtplib.SMTP('smtp-mail.outlook.com', 587) File "C:\Users\sysadmin\AppData\Local\Programs\Python\Python37-32\lib\smtplib.py",
line 251, in init
(code, msg) = self.connect(host, port) File "C:\Users\sysadmin\AppData\Local\Programs\Python\Python37-32\lib\smtplib.py",
line 336, in connect
self.sock = self._get_socket(host, port, self.timeout) File "C:\Users\sysadmin\AppData\Local\Programs\Python\Python37-32\lib\smtplib.py",
line 307, in _get_socket
self.source_address) File "C:\Users\sysadmin\AppData\Local\Programs\Python\Python37-32\lib\socket.py",
line 727, in create_connection
raise err File "C:\Users\sysadmin\AppData\Local\Programs\Python\Python37-32\lib\socket.py",
line 716, in create_connection
sock.connect(sa) 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
Can you just try this bit? This should print the exceptions and we can fix the problem once we know the problem nature.
import smtplib
global server
try:
server = smtplib.SMTP_SSL( < host >, < port >)
except Exception as e:
print("{}".format(e))
try:
server.login("your username", "your password")
except Exception as e:
print("{}".format(e))
server.sendmail(
"from#address.com",
"to#address.com",
"this message is from python")
server.quit()

Python SMTP error: "(10013, 'Permission denied')"

So I have this Python send-email file that sends an email (the text from a file) to a recipient specified inside the code:
import smtplib
from email.mime.text import MIMEText
msgContent = open(Sourcefilelocation, "rb")
msg = MIMEText(spam.read())
msgContent.close()
msg['Subject'] = SUBJECT
msg['From'] = FROM_CLIENT_EMAIL
msg['To'] = TO_CLIENT_EMAIL
#THE ERROR BELOW
s = smtplib.SMTP('localhost')
I understand that there is no mail server on localhost, but how do I make a mail server on that and if I can't then why does s = smtplib.SMTP('gmail.com') take so long if it even works? What do I need to make it work? Any help is appreciated.
output: >> Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
s = smtplib.SMTP('gmail.com')
File "C:\Python25\lib\smtplib.py", line 244, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python25\lib\smtplib.py", line 310, in connect
raise socket.error, msg
error: (10013, 'Permission denied')
And the gmail smtp code takes too long.

Send email from server python

I am trying to send an email form my server with python, I asked my server provider what port to use for this and they said "choose SMTP Ports 465 (Secure SSL/TLS outgoing server) , 25 ( Non-SSL outgoing server)." Not sure what this exactly means but currently I am using 25, here is my code
#! /usr/bin/python
import smtplib
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 25)
#Next, log in to the server
server.login("youremailusername", "password")
#Send the mail
msg = "\nHello!" # The /n separates the message from the headers
server.sendmail("you#gmail.com", "target#example.com", msg)
I filled in my username (which is my email address right) and password,a dn the target but it is not working, when I try to navigate to the url where my py script is, it just doesn't load. I have an internet connection cause I am loving other things, and go to other pages on my server. I have also tried running with cron jobs but that also doesn't work.
The permissions on the script are 0755, is there a problem with the script?
When i ran with cron jobs here is the traceback
Traceback (most recent call last):
File "/home/spencerf/public_html/cgi-bin/send_email.py", line 6, in <module>
server = smtplib.SMTP('smtp.gmail.com', 25)
File "/usr/lib64/python2.6/smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib64/python2.6/smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib64/python2.6/smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "/usr/lib64/python2.6/socket.py", line 567, in create_connection
raise error, msg
socket.error: [Errno 101] Network is unreachable
Thanks for the help in advance.
EDIT
here is updated error log with the port at 587
Traceback (most recent call last):
File "/home/spencerf/public_html/cgi-bin/send_email.py", line 7, in <module>
server = smtplib.SMTP('smtp.gmail.com', 587)
File "/usr/lib64/python2.6/smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib64/python2.6/smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib64/python2.6/smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "/usr/lib64/python2.6/socket.py", line 567, in create_connection
raise error, msg
socket.error: [Errno 101] Network is unreachable
EDIT 2
When I had server = smtplib.SMTP('telnet smtp.gmail.com', 587)
I got this error
Traceback (most recent call last):
File "/home/spencerf/public_html/cgi-bin/send_email.py", line 8, in <module>
server = smtplib.SMTP('telnet smtp.gmail.com', 587)
File "/usr/lib64/python2.6/smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib64/python2.6/smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib64/python2.6/smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "/usr/lib64/python2.6/socket.py", line 553, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno -2] Name or service not known
BUG:
First of all you are using gmail server not your company server to send mail .For gmail server the output port is 587
The code:
Due to security issues gmail blocks accessing mail via code or program
But still you can use gmail to send mail via code if you do the following things
What i have done in code :
1.Added a error object to get the error message
import smtplib
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
#Next, log in to the server
server.login("youremailusername", "password")
#Send the mail
msg = "\nHello!" # The /n separates the message from the headers
server.sendmail("you#gmail.com", "target#example.com", msg)
print "Successfully sent email"
except smtplib.SMTPException,error:
print str(error)
print "Error: unable to send email"
If u ran this code u would see a error message like this stating that google is not allowing u to login via code
Things to change in gmail:
1.Login to gmail
2.Go to this link https://www.google.com/settings/security/lesssecureapps
3.Click enable then retry the code
Hopes it help :)
But there are security threats if u enable it
Updated
import smtplib
try:
content = 'test'
mail = smtplib.SMTP('smtp.gmail.com',587)
mail.ehlo()
mail.starttls()
mail.login("ABC#gmail.com", "password")
mail.sendmail("ABC#gmail.com", "recivermailaddress", content)
mail.quit
print "Successfully sent email"
except smtplib.SMTPException,error:
print str(error)
In python, please download yagmail (disclaimer: I'm the developer):
pip install yagmail
It is then simply a matter of:
import yagmail
yag = yagmail.SMTP("you#gmail.com", "password")
yag.send("target#example.com", 'This is the subject', 'Hello!')
I guess it mostly just has to do with the fact that you gave a wrong port (smtp.gmail.com is not at 25).
On the github you can also see a common list of errors.

Error during sending mail

I try to send mail via python. I got a function:
def mail():
fromaddr = 'mymail#gmail.com'
toaddrs = 'targetmail#o2.pl'
msg = 'There was a terrible error that occured and I wanted you to know!'
# Credentials (if needed)
username = 'mymail#gmail.com'
password = 'password'
# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.ehlo()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
When I try to execute this function it whows me WinError 10060. Error text below:
Traceback (most recent call last):
File "C:\python-factory\ServiceChecker\main\mainBlock.py", line 75, in <module> mail()
File "C:\python-factory\ServiceChecker\main\mainBlock.py", line 65, in mail server = smtplib.SMTP('smtp.gmail.com:587')
File "C:\Python34\Lib\smtplib.py", line 242, in __init__ (code, msg) = self.connect(host, port)
File "C:\Python34\Lib\smtplib.py", line 321, in connect self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python34\Lib\smtplib.py", line 292, in _get_socket self.source_address)
File "C:\Python34\Lib\socket.py", line 509, in create_connection raise err
File "C:\Python34\Lib\socket.py", line 500, in create_connection sock.connect(sa)
TimeoutError: [WinError 10060]
I don't know where is problem... i tried many mail servers (gmail,o2,wp,) all of them returned the same error. I tried also other available solutions in the internet to send mail via pyython.... the same problem...
Please help
According to your posted backtrace, you are failing at the line
server = smtplib.SMTP('smtp.gmail.com:587')
I've run that line and it works for me. The clue is in the TimeoutError. I believe you are having networking problems and the code itself is fine.
You do have an extra call to ehlo but as it stands you are not getting that far.
Additionally, it would probably be better to pass the port number as a separate argument, rather than using a colon to split it. E.g.
server = smtplib.SMTP(host='smtp.gmail.com', port=587)
The documentation for smptlib is here: https://docs.python.org/2/library/smtplib.html
Try removing the second server.ehlo() . The one just before login. That worked for me.
toaddrs should be a list
toaddrs = ['targetmail#o2.pl']

Categories

Resources