OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Title: "IMAP Connection Error: 'Socket error: 0x02: Connection not allowed by ruleset' when using SOCKS5 Proxy in Python"

  • Thread starter Thread starter Zeus
  • Start date Start date
Z

Zeus

Guest
I'm trying to connect to an IMAP server through a SOCKS5 proxy using Python. However, I keep encountering the error: Socket error: 0x02: Connection not allowed by ruleset. Below is the code I'm using:

Code:
import imaplib
import socks
import socket
import ssl
import requests
from requests.auth import HTTPProxyAuth

# Proxy configuration
PROXY_HOST = "178.xx.xx.xxx"
PROXY_PORT = 10300
PROXY_USERNAME = "xxx"
PROXY_PASSWORD = "xxx"

# Email configuration
IMAP_SERVER = "imap.gmx.com"
IMAP_PORT = 993
EMAIL = "[email protected]"
PASSWORD = "xxxxx"

def check_proxy_connection():
    session = requests.Session()
    session.proxies = {
        "http": f"http://{PROXY_USERNAME}:{PROXY_PASSWORD}@{PROXY_HOST}:{PROXY_PORT}",
        "https": f"http://{PROXY_USERNAME}:{PROXY_PASSWORD}@{PROXY_HOST}:{PROXY_PORT}"
    }
    try:
        response = session.get("http://api.myip.com", timeout=10)
        response.raise_for_status()
        return response.json()
    except requests.RequestException as e:
        print(f"An error occurred: {e}")
        return None

# Check the proxy connection
proxy_response = check_proxy_connection()
if proxy_response:
    print(f"Proxy is working. Response from api.myip.com:\n{proxy_response}")
else:
    print("Proxy is not working. Exiting the script.")
    exit()

# Set up the proxy with authentication
socks.set_default_proxy(
    socks.SOCKS5,
    PROXY_HOST,
    PROXY_PORT,
    username=PROXY_USERNAME,
    password=PROXY_PASSWORD
)
socket.socket = socks.socksocket

try:
    # Create an SSL context
    ssl_context = ssl.create_default_context()

    # Connect to the IMAP server through the proxy
    imap_client = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT, ssl_context=ssl_context)

    # Login to the email account
    imap_client.login(EMAIL, PASSWORD)
    print("Successfully logged in")

    # List available mailboxes
    status, mailboxes = imap_client.list()
    if status == 'OK':
        print("Available mailboxes:")
        for mailbox in mailboxes:
            print(mailbox.decode())

    # Select the inbox
    imap_client.select('INBOX')

    # Search for emails
    status, messages = imap_client.search(None, 'ALL')
    if status == 'OK':
        message_numbers = messages[0].split()
        print(f"Number of emails in inbox: {len(message_numbers)}")

        # Fetch the latest email
        if message_numbers:
            latest_email_id = message_numbers[-1]
            status, msg_data = imap_client.fetch(latest_email_id, '(RFC822)')
            if status == 'OK':
                print("Latest email fetched successfully")
                # Here you can process the email content if needed
                # raw_email = msg_data[0][1]
                # email_message = email.message_from_bytes(raw_email)
                # ...

except imaplib.IMAP4.error as e:
    print(f"An IMAP error occurred: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
finally:
    try:
        imap_client.logout()
        print("Logged out and closed the connection")
    except Exception as e:
        print(f"Failed to close the connection cleanly: {e}")

Error Message: An unexpected error occurred: Socket error: 0x02: Connection not allowed by ruleset

Steps I've Taken:

Code:
Verified that the proxy works by checking the response from http://api.myip.com.
Attempted to connect to the IMAP server through the proxy using imaplib.IMAP4_SSL.

Environment:

Code:
Python version: 3.12.3
pysocks library for proxy handling
IMAP server: imap.gmx.com
Proxy: SOCKS5 with authentication

What could be causing the "Connection not allowed by ruleset" error when connecting through the SOCKS5 proxy? Are there any additional steps I need to take to properly configure the proxy for IMAP connections?
<p>I'm trying to connect to an IMAP server through a SOCKS5 proxy using Python. However, I keep encountering the error: Socket error: 0x02: Connection not allowed by ruleset. Below is the code I'm using:</p>
<pre><code>import imaplib
import socks
import socket
import ssl
import requests
from requests.auth import HTTPProxyAuth

# Proxy configuration
PROXY_HOST = "178.xx.xx.xxx"
PROXY_PORT = 10300
PROXY_USERNAME = "xxx"
PROXY_PASSWORD = "xxx"

# Email configuration
IMAP_SERVER = "imap.gmx.com"
IMAP_PORT = 993
EMAIL = "[email protected]"
PASSWORD = "xxxxx"

def check_proxy_connection():
session = requests.Session()
session.proxies = {
"http": f"http://{PROXY_USERNAME}:{PROXY_PASSWORD}@{PROXY_HOST}:{PROXY_PORT}",
"https": f"http://{PROXY_USERNAME}:{PROXY_PASSWORD}@{PROXY_HOST}:{PROXY_PORT}"
}
try:
response = session.get("http://api.myip.com", timeout=10)
response.raise_for_status()
return response.json()
except requests.RequestException as e:
print(f"An error occurred: {e}")
return None

# Check the proxy connection
proxy_response = check_proxy_connection()
if proxy_response:
print(f"Proxy is working. Response from api.myip.com:\n{proxy_response}")
else:
print("Proxy is not working. Exiting the script.")
exit()

# Set up the proxy with authentication
socks.set_default_proxy(
socks.SOCKS5,
PROXY_HOST,
PROXY_PORT,
username=PROXY_USERNAME,
password=PROXY_PASSWORD
)
socket.socket = socks.socksocket

try:
# Create an SSL context
ssl_context = ssl.create_default_context()

# Connect to the IMAP server through the proxy
imap_client = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT, ssl_context=ssl_context)

# Login to the email account
imap_client.login(EMAIL, PASSWORD)
print("Successfully logged in")

# List available mailboxes
status, mailboxes = imap_client.list()
if status == 'OK':
print("Available mailboxes:")
for mailbox in mailboxes:
print(mailbox.decode())

# Select the inbox
imap_client.select('INBOX')

# Search for emails
status, messages = imap_client.search(None, 'ALL')
if status == 'OK':
message_numbers = messages[0].split()
print(f"Number of emails in inbox: {len(message_numbers)}")

# Fetch the latest email
if message_numbers:
latest_email_id = message_numbers[-1]
status, msg_data = imap_client.fetch(latest_email_id, '(RFC822)')
if status == 'OK':
print("Latest email fetched successfully")
# Here you can process the email content if needed
# raw_email = msg_data[0][1]
# email_message = email.message_from_bytes(raw_email)
# ...

except imaplib.IMAP4.error as e:
print(f"An IMAP error occurred: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
try:
imap_client.logout()
print("Logged out and closed the connection")
except Exception as e:
print(f"Failed to close the connection cleanly: {e}")
</code></pre>
<p>Error Message:
<code>An unexpected error occurred: Socket error: 0x02: Connection not allowed by ruleset</code></p>
<p>Steps I've Taken:</p>
<pre><code>Verified that the proxy works by checking the response from http://api.myip.com.
Attempted to connect to the IMAP server through the proxy using imaplib.IMAP4_SSL.
</code></pre>
<p>Environment:</p>
<pre><code>Python version: 3.12.3
pysocks library for proxy handling
IMAP server: imap.gmx.com
Proxy: SOCKS5 with authentication
</code></pre>
<p>What could be causing the "Connection not allowed by ruleset" error when connecting through the SOCKS5 proxy?
Are there any additional steps I need to take to properly configure the proxy for IMAP connections?</p>
 

Latest posts

B
Replies
0
Views
1
Blundering Ecologist
B
Top