Title: “IMAP Connection Error: ‘Socket error: 0x02: Connection not allowed by ruleset’ when using SOCKS5 Proxy in Python”

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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>
<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>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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>
<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>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Python version: 3.12.3
pysocks library for proxy handling
IMAP server: imap.gmx.com
Proxy: SOCKS5 with authentication
</code>
<code>Python version: 3.12.3 pysocks library for proxy handling IMAP server: imap.gmx.com Proxy: SOCKS5 with authentication </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?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật