2016-06-10 97 views
0

這是我的第一個Python代碼,請原諒。 這就是我寫的。如何根據主題下載gmail附件?錯誤:連接到imap.gmail.com時「沒有路由到主機」

import imaplib 
import email 
import os 
import getpass 

email = 'br******@******.com' 
password = getpass.getpass('Enter your password: ') 
mail = 'imap.gmail.com' 
flag = '(RFC822)' 
svdir = 'c:/Users/' 

m = imaplib.IMAP4(mail) 
m.login(email,password) 
m.select('inbox') 
typ, msgs = m.search(None, 'subject:resume has:attachment') 
msgs = msgs[0].split() 
for emailid in msgs: 
resp, data = m.fetch(emailid, "(RFC822)") 
email_body = data[0][1] 
mail = email.message_from_string(email_body) 
if mail.get_content_maintype() != 'multipart': 
    continue 
for part in mail.walk(): 
if part.get_content_maintype() == 'multipart': 
    continue 
if part.get('Content-Disposition') is None: 
    continue 
filename=part.get_filename() 
if filename is not None: 
sv_path = os.path.join(svdir, filename) 
if not os.path.isfile(sv_path): 
    print (sv_path) 
fp = open(sv_path, 'wb') 
fp.write(part.get_payload(decode=True)) 
fp.close() 

但我得到這個錯誤。

Traceback (most recent call last): 
    File "/Users/Documents/Fetch_Attchments.py", line 12, in  <module> 
    m = imaplib.IMAP4(mail) 
    File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/imaplib.py", line  197, in __init__ 
    self.open(host, port) 
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/imaplib.py", line 294, in open 
    self.sock = self._create_socket() 
    File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/imaplib.py", line 284, in _create_socket 
    return socket.create_connection((self.host, self.port)) 
    File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socket.py", line 711, in create_connection 
    raise err 
    File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socket.py", line 702, in create_connection 
    sock.connect(sa) 
OSError: [Errno 65] No route to host 

我按主題過濾郵件並將附件保存到特定位置。請注意,主題條件將只過濾一條消息。

+0

請修正縮進爲四個空格,這將使得代碼更易讀,它的縮進Python代碼的正式方法。 – linusg

+1

@linusg無論如何你可以忽略大部分的代碼;它在12號線失敗。 – melpomene

回答

0

Gmail不允許在純文本端口上進行連接。 SSL/TLS是必需的。

你將需要:

m = imaplib.IMAP4_SSL("imap.gmail.com", 993) 
相關問題