如何根据主题下载Gmail附件?错误:连接到imap.gmail.com时“无主机路由”

时间:2016-06-10 14:31:41

标签: python python-2.7 python-3.x gmail-imap imaplib

这是我的第一个python代码,请原谅。 这就是我写的。

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

我按主题过滤邮件并将附件保存到特定位置。请注意,主题条件只会过滤一条消息。

1 个答案:

答案 0 :(得分:0)

Gmail不允许在纯文本端口上进行连接。需要SSL / TLS。

您将需要:

m = imaplib.IMAP4_SSL("imap.gmail.com", 993)