Python smtplib установить таймаут без сбоя - PullRequest
0 голосов
/ 26 сентября 2018

Я пытаюсь установить тайм-аут для каждого соединения, которое проверяю, но как только время ожидания истекло, я хочу, чтобы оно продолжало до следующего.

Мой код:

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import socket
 

def AuthSMTP(password, username, smtphost):
	msg = MIMEMultipart()
	message = ("The Host '%s' worked out Successfully and send emails." % (smtphost))
	msg['From'] = "test@test.com"
	msg['To'] = "kingplease9@gmail.com"
	msg['Subject'] = ("SMTP Server : %s" % (smtphost))
	 
	#Add the message body to the object instance
	msg.attach(MIMEText(message, 'plain'))
	 
	#Create the server connection
	server = smtplib.SMTP(smtphost)
	 
	#Switch the connection over to TLS encryption
	server.starttls()
	 
	try :
		socket.setdefaulttimeout(30)
		server.login(username, password)
		server.sendmail(msg['From'], msg['To'], msg.as_string())
		return True
	except Exception as e:
		return False
	server.quit()
 

with open("servers.txt", "r") as ins:
	for line in ins:
		line = line.split(":")
		##print(line)
		print ("Trying to connect: %s" % (line[0]))
		smtp_host = ("%s:%s" % (line[0],line[1]))
		username = line[2]
		password = line[3].replace("\n","")
		if AuthSMTP(password, username, smtp_host):
			print ("[%s] Connected Successfully." % (smtp_host))
		else:
				print ("[%s] Failed to connect." % (smtp_host))

Traceback:

Trying to connect: mail.municipalidadlajoya.gob.pe
[mail.municipalidadlajoya.gob.pe:587] Connected Successfully.
Trying to connect: mail.planerp.ec
[mail.planerp.ec:587] Connected Successfully.
Trying to connect: mail.salinas.gob.ec
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python37-32\lib\smtplib.py", line 387, in getreply
    line = self.file.readline(_MAXLINE + 1)
  File "C:\Program Files (x86)\Python37-32\lib\socket.py", line 589, in readinto
    return self._sock.recv_into(b)
socket.timeout: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\dfu\Desktop\Maor\Python\SMTP\smtpchecker.py", line 41, in <module>
    if AuthSMTP(password, username, smtp_host):
  File "C:\Users\df\Desktop\Maor\Python\SMTP\smtpchecker.py", line 18, in AuthSMTP
    server = smtplib.SMTP(smtphost)
  File "C:\Program Files (x86)\Python37-32\lib\smtplib.py", line 251, in __init__
    (code, msg) = self.connect(host, port)
  File "C:\Program Files (x86)\Python37-32\lib\smtplib.py", line 338, in connect
    (code, msg) = self.getreply()
  File "C:\Program Files (x86)\Python37-32\lib\smtplib.py", line 391, in getreply
    + str(e))
smtplib.SMTPServerDisconnected: Connection unexpectedly closed: timed out
[Finished in 34.8s with exit code 1]
[shell_cmd: python -u "C:\Users\df\Desktop\Maor\Python\SMTP\smtpchecker.py"]
[dir: C:\Users\df\Desktop\Maor\Python\SMTP]
[path: C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Program Files (x86)\Python37-32\Scripts\;C:\Program Files (x86)\Python37-32\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;D:\Program Files\Git\cmd;C:\Users\df df\AppData\Local\Microsoft\WindowsApps;]

Его сбой, как только сокет достигнет 30 секунд тайм-аута, затем разрушит весь цикл.

Надеюсь, вы понимаете меня, ребята, и спасибо продвинутым ребятам:)

...