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

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.

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.

I am getting the error WinError 10057 in python 3.10.1 as I use it for sockets

I am new to network programming in python and I am trying to create a payment gateway for a project. I have run into an error with sending and receiving data between servers.
Here is my code for both the server and the client:
Server Script:
import socket
banka_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
banka_socket.bind(("192.168.0.22", 8082))
banka_socket.listen()
print("Waiting for bank A socket...")
connection_socket, address = banka_socket.accept()
print("Bank A connected")
message = banka_socket.recv(1024).decode()
print(message)
Client Script:
import socket
gateway_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
gateway_socket.connect(("192.168.0.22", 8082))
print("Gateway connected")
client_data = "hello"
message = client_data.encode()
gateway_socket.send(message)
The data is being sent and received on the same computer. I ran the server script and then I ran the client script. That's when I received the following error:
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
The code with the error was:
message = banka_socket.recv(1024).decode()
Please let me know how I fix my code, I've been struggling with this for a while now.

while sending the mail using smtplib in python got the error (11004, 'getaddrinfo failed')

I'm sending a mail using a python script on a development server which don't have internet connection but i check the connectivity with the SMTP server by pinging the server and it is connected. But i'm getting error (11004, getaddrinfo failed) while connecting to it using smtplib.
Please help me in this issue!
Below is the code im using
msg = MIMEMultipart()
msg["From"] = "sender"
msg["To"] = 'recipient'
msg["Subject"] = "Testing Email"
message = 'Hi,\n \nThis is testing mail.'
ctype, encoding = mimetypes.guess_type(file)
if ctype is None or encoding is not None:
ctype = "application/octet-stream"
maintype, subtype = ctype.split("/", 1)
fp = open(file, "rb")
attachment = MIMEBase(maintype, subtype)
attachment.set_payload(fp.read())
fp.close()
encoders.encode_base64(attachment)
attachment.add_header("Content-Disposition", "attachment", filename='report.xlsx')
msg.attach(MIMEText(message, 'plain'))
msg.attach(attachment)
try:
server = smtplib.SMTP(server_name)
server.set_debuglevel(0)
server.sendmail(sender, receiver, msg.as_string())
server.quit()
except Exception as e:
print(e.args)
Try this:
server = smtplib.SMTP("smtp.google.com", 587)
server.starttls()
server.login(email, password)
server.sendmail(email, email, message)
server.quit()

How to send response back to initiator

so i am trying to set up a FIX server that will serve me to accept FIX messages.
i managed to receive messages from a demo client that i made.
i want to perform an action according to the received message and then return a response to the initiator.
i have added the code that i use, it somehow sends it through the acceptor back to the initiator.
import quickfix as fix
def create_fix_response_for_wm(self, session_id, message, api_response):
try:
report = quickfix50sp2.ExecutionReport()
report.setField(fix.Text(api_response.text))
report.setField(fix.ListID(message.getField(66)))
if message.getFieldIfSet(fix.OrderID()):
report.setField(fix.OrderID(message.getField(14)))
elif message.getFieldIfSet(fix.ListID()):
report.setField(fix.OrderID(message.getField(66)))
fix.Session.sendToTarget(report, session_id)
except Exception as e:
logger.exception(f'could not create response')
so after looking and testing a couple of times this is what i found.
import quickfix as fix
def create_fix_response_for_wm(self, session_id, message, api_response):
try:
report = quickfix50sp2.ExecutionReport()
report.setField(fix.Text(api_response.text))
report.setField(fix.ListID(message.getField(66)))
if message.getFieldIfSet(fix.OrderID()):
report.setField(fix.OrderID(message.getField(14)))
elif message.getFieldIfSet(fix.ListID()):
report.setField(fix.OrderID(message.getField(66)))
fix.Session.sendToTarget(report, session_id)
except Exception as e:
logger.exception(f'could not create response')
session_id = should be a SessionID object which can be built like this:
session_id = fix.SessionID("FIXT.1.1", <ACCEPTOR - SenderCompID of the acceptor configuration>, <INITIATOR - TargetCompID in the acceptor configuration >)
configuration example:
[SESSION]
SocketAcceptPort=12000
StartDay=sunday
EndDay=friday
AppDataDictionary=./glossary/FIX50SP2.xml
TransportDataDictionary=./glossary/FIXT11.xml
DefaultApplVerID=FIX.5.0SP2
BeginString=FIXT.1.1
SenderCompID=MYACCEPTOR
TargetCompID=CLIENT
session_id = fix.SessionID("FIXT.1.1","MYACCEPTOR" , "CLIENT") - in our case
you you this sessionID object when sending.
fix.Session.sendToTarget(<YOUR MESSAGE>, session_id)

Error in server-running while acessing web-page

We are assigned to write a simple app including three pages + mainpage that is going to have links to all other pages (content cut for the version here). Below is fully-functional code, that accomplishes all of that. Nevertheless there is an error randomly arising while running server, which, however, does not affect the work of the server at all.
I have tried to look at what is going on with the requests sent to the server and it showed me that periodically instead of one request, server receives two
import socketserver
from server import ThreadedTcpServer
from request import Request
from response import Response
class MyTCPHandler(socketserver.StreamRequestHandler):
def handle(self):
print('Connected from: ' + str(self.client_address))
print('==========Request===========')
request = Request(self.rfile)
print(request.request_line + '\n')
response = Response(self.wfile)
response.add_header('Content-Type', 'text/html')
response.add_header('Connection', 'close')
if request.path == '/':
...
response.send()
ThreadedTcpServer.allow_reuse_address = True
server = ThreadedTcpServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
server.server_close()
In the log of the server I expect to see only request_lines and print of connection info,but sometimes instead of one request it shows two from different client_addresses and two arising exceptions like:
Connected from: ('127.0.0.1', 34962)
==========Request===========
GET /three HTTP/1.1
Connected from: ('127.0.0.1', 34966)
==========Request===========
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 34966)
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 34962)
and huge traceback starting from socketserver module and ending up in my request class where it cannot parse request_line.

Resources