从Python连接到Gmail

时间:2013-07-17 19:03:43

标签: python gmail imaplib

我一直在尝试使用python连接到我的Gmail帐户。 imap已启用。

import imaplib

imap_server = imaplib.IMAP4_SSL("imap.gmail.com",993)
# also tried imap_server = imaplib.IMAP4_SSL("imap.gmail.com"), doesnt work. 

回溯是:

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    imap_server = imaplib.IMAP4_SSL("imap.gmail.com",993)
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/imaplib.py", line 1202, in __init__
    IMAP4.__init__(self, host, port)
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/imaplib.py", line 172, in __init__
    self.open(host, port)
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/imaplib.py", line 1217, in open
    IMAP4.open(self, host, port)
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/imaplib.py", line 248, in open
    self.sock = self._create_socket()
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/imaplib.py", line 1205, in _create_socket
    sock = IMAP4._create_socket(self)
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/imaplib.py", line 238, in _create_socket
    return socket.create_connection((self.host, self.port))
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/socket.py", line 435, in create_connection
    raise err
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/socket.py", line 426, in create_connection
    sock.connect(sa)
OSError: [Errno 65] No route to host

1 个答案:

答案 0 :(得分:7)

OSError: [Errno 65] No route to host的含义是什么:你无法从你的机器上到达那台机器。

您可以通过打开终端/ DOS提示符并输入以下内容从Python外部进行测试:

ping imap.gmail.com

这可能实际上是一个名称查找错误,而且你在某种程度上为imap.gmail.com获取了一个错误的地址。所以,为了确保,也要通过IP地址检查:

ping 74.125.129.108
ping 74.125.129.109

如果ping有效,您可以检查您的路由器是否出于某种原因阻止对主机的TCP访问,例如:

telnet imap.gmail.com

如果它正在工作,这应该挂了很长时间,或者给你一个拒绝连接的错误;如果它给你一个无路由到主机的错误,那就是你遇到的同样问题。

您的路由器也可能专门阻止端口993.您也可以测试它:

telnet imap.gmail.com 993

如果没有“连接到gmail-imap.l.google.com”这样的内容,也会出现同样的问题。

无论如何,一旦您确认这是系统或网络配置问题,而不是编程问题,请在相应的站点上寻求有关系统的帮助。