Python - 通过 Socks 连接到 IMAP

Python - Connect to IMAP through Socks

我正在寻找使用 Socks 代理连接到 IMAP 的解决方案。我发现它最优雅的方式是对 IMAP4 lib 的 PySocks 进行包装(您可以在此处找到此代码的要点:https://gist.github.com/sstevan/efccf3d5d3e73039c21aa848353ff52f)。

无法在python3中实现的问题。对我来说,继承似乎有问题:

主脚本调用 SocksIMAP4SSL 包装器

    mailbox = SocksIMAP4SSL(host=imap_server, port=imap_port,
                            proxy_addr=proxy_addr, proxy_port=proxy_port, proxy_type=proxy_type)

SocksIMAP4SSL的init实现

    def __init__(self, host='', port=IMAP4_SSL_PORT, keyfile=None, certfile=None, ssl_context=None, proxy_addr=None,
                 proxy_port=None, rdns=True, username=None, password=None, proxy_type="socks5"):
        .......
        SocksIMAP4.__init__(self, host, port, proxy_addr=proxy_addr, proxy_port=proxy_port,
                            rdns=rdns, username=username, password=password, proxy_type=proxy_type)

SocksIMAP4的init实现

    def __init__(self, host, port=IMAP4_PORT, proxy_addr=None, proxy_port=None,
                 rdns=True, username=None, password=None, proxy_type="socks5"):

        self.proxy_addr = proxy_addr
        self.proxy_port = proxy_port
        self.rdns = rdns
        self.username = username
        self.password = password
        self.proxy_type = SocksIMAP4.PROXY_TYPES[proxy_type.lower()]

        IMAP4.__init__(self, host, port)

当我运行这段代码时,我得到一个错误:

Traceback (most recent call last):
  File "/Users/lavidaloca/Programming/Projects/twitter_checkmat/twitter.py", line 691, in <module>
    hotmail = Hotmail('similargatorade3@hotmail.com', 'C9C48RyO', proxy)
  File "/Users/lavidaloca/Programming/Projects/twitter_checkmat/hotmail.py", line 78, in __init__
    self.mail = SocksIMAP4SSL(host=self.imap_server, port=self.imap_port, proxy_addr=proxy.host, proxy_port=proxy.port, username=proxy.login, password=proxy.password)
  File "/Users/lavidaloca/Programming/Projects/twitter_checkmat/hotmail.py", line 59, in __init__
    SocksIMAP4.__init__(self, host, port, proxy_addr=proxy_addr, proxy_port=proxy_port,
  File "/Users/lavidaloca/Programming/Projects/twitter_checkmat/hotmail.py", line 34, in __init__
    IMAP4.__init__(self, host, port)
  File "/opt/homebrew/Cellar/python@3.9/3.9.12_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/imaplib.py", line 202, in __init__
    self.open(host, port, timeout)
TypeError: open() takes from 1 to 3 positional arguments but 4 were given

看起来 IMAP4 库的原始 init 方法接收子类的初始化参数。

如果您能告诉我如何修复此代码或给我另一个通过袜子连接到 imap 的解决方案,我将不胜感激。

Python imaplib 模块在Python 3.9 中更改,SocksIMAP4 模块尚未更新。这就是与模块的内部结构混为一谈的危险。您可以尝试通过向 SocksIMAP4.open 添加您忽略的第三个参数来破解它。

您也可以向 SocksIMAP4 人员提交错误报告。