I have a Python script that sends emails using SMTP. When I configure it to use a SOCKS5 proxy, specifically 202.142.177.156:67621, I encounter a RangeError during execution. However, when I remove the proxy configuration, the script works correctly. The SMTP server I’m connecting to on port 465, Unexpected error occurred: connect(): port must be 0-65535.
I attempted to set up the SOCKS5 proxy using the socks library in Python, as shown in the code snippet below. I expected the email to be sent successfully through the proxy, but instead, I encountered a RangeError. Without the proxy, the script executes without errors
@classmethod
def SEND_FINAL_EMAIL(cls, subject, body, sending_to, max_retries=1):
sending_to = "m"
use_smtp = False
if "reg" in sending_to or "s" in sending_to or "rest" in sending_to or "test" in sending_to:
use_smtp = True
try:
proxy_ip = "202.142.177.156"
proxy_port = 67621
socks.setdefaultproxy(socks.SOCKS5, proxy_ip, proxy_port)
socket.socket = socks.socksocket
except Exception as e:
return "Error in setting proxy: " + str(e)
if use_smtp:
cls.smtp_server = ""
cls.smtp_port = 465
cls.email_address = ""
cls.app_password = ""
else:
cls.smtp_server = ""
cls.smtp_port = 587
cls.email_address = ""
cls.app_password = ""
try:
print("Sending email to:", sending_to)
message = MIMEMultipart()
message["From"] = cls.email_address
message["To"] = sending_to
message["Subject"] = subject
message.attach(MIMEText(body, "plain"))
# Attempt to establish the SMTP connection
with smtplib.SMTP_SSL(cls.smtp_server, cls.smtp_port) as server:
server.login(cls.email_address, cls.app_password)
# Send the email
server.sendmail(cls.email_address, sending_to, message.as_string())
return "Email sent successfully."
except smtplib.SMTPException as e:
print("Error in sending email (Attempt ): {e}")
except Exception as e:
return "Unexpected error occurred: " + str(e)