主机在使用 Gmail API 和 Python 发送电子邮件时中止连接

Host aborting connection while sending an email using Gmail API and Python

我不会用整个代码来打扰你 - 这是我的第一个问题所以请耐心等待。

我正在尝试使用 Gmail API 发送附有 .zip 文件的电子邮件。整个想法是通过 Gmail 自动发送带有数据的电子邮件,同时保持标准的安全级别。

这是我的身份验证方式:

def authenticate(self):
        CLIENT_SECRET_FILE = 'client_secrets.json'
        OAUTH_SCOPE = 'https://www.googleapis.com/auth/gmail.compose'
        STORAGE = Storage('gmail.storage')
        flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, scope=OAUTH_SCOPE)
        http = httplib2.Http()
        credentials = STORAGE.get()
        if credentials is None or credentials.invalid:
            credentials = run(flow, STORAGE, http=http)
        http = credentials.authorize(http)
        self.service = build('gmail', 'v1', http=http)

然后使用 Google 给出的例子,几乎原样,我准备我的消息:

def CreateMessageWithAttachment(self, sender, to, subject, message_text, file_strings):
        message = MIMEMultipart()
        message['to'] = to
        message['from'] = sender
        message['subject'] = subject

        msg = MIMEText(message_text)
        message.attach(msg)

        for path in file_strings:
            content_type, encoding = mimetypes.guess_type(path)

            main_type, sub_type = content_type.split('/', 1)
            fp = open(path, 'rb')
            msg = MIMEBase(main_type, sub_type)
            msg.set_payload(fp.read())
            fp.close()
            msg.add_header('Content-Disposition', 'attachment', filename=path.split("\")[-1])
            message.attach(msg)

        return  {'raw': base64.urlsafe_b64encode(message.as_string())}

最后我再次使用几乎完全相同的示例发送它:

 def SendMessage(self, message, address):
        try:
            message = (self.service.users().messages().send(userId=self.user_id, body=message).execute())
            return "Message to %s successfuly sent at: %s." %(address , datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") )
        except errors.HttpError, error:
            return  'An error occurred: %s' % error

因此,我得到了一个大小为 9.8MB 的特定 .zip 文件的可爱文字墙(我能够通过 gmail 手动发送它):

 Traceback (most recent call last):
  File "DeliveryManager.py", line 264, in <module>
    dispatch.run()
  File "DeliveryManager.py", line 180, in run
    self.sendMessages()
  File "DeliveryManager.py", line 248, in sendMessages
    log = self.sender.SendMessage(message, address)
  File "DeliveryManager.py", line 79, in SendMessage
    message = (self.service.users().messages().send(userId=self.user_id, body=message).execute())
  File "c:\python27\lib\site-packages\oauth2client\util.py", line 135, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "c:\python27\lib\site-packages\googleapiclient\http.py", line 716, in execute
    body=self.body, headers=self.headers)
  File "c:\python27\lib\site-packages\oauth2client\util.py", line 135, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "c:\python27\lib\site-packages\oauth2client\client.py", line 547, in new_request
    redirections, connection_type)
  File "c:\python27\lib\site-packages\httplib2\__init__.py", line 1593, in request
    (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
  File "c:\python27\lib\site-packages\httplib2\__init__.py", line 1335, in _request
    (response, content) = self._conn_request(conn, request_uri, method, body, headers)
  File "c:\python27\lib\site-packages\httplib2\__init__.py", line 1291, in _conn_request
    response = conn.getresponse()
  File "c:\python27\lib\httplib.py", line 1045, in getresponse
    response.begin()
  File "c:\python27\lib\httplib.py", line 409, in begin
    version, status, reason = self._read_status()
  File "c:\python27\lib\httplib.py", line 365, in _read_status
    line = self.fp.readline(_MAXLINE + 1)
  File "c:\python27\lib\socket.py", line 476, in readline
    data = self._sock.recv(self._rbufsize)
  File "c:\python27\lib\ssl.py", line 241, in recv
    return self.read(buflen)
  File "c:\python27\lib\ssl.py", line 160, in read
    return self._sslobj.read(len)
socket.error: [Errno 10053] An established connection was aborted by the software in your host machine
>Exit code: 1

我想我的消息格式不正确,但我不知道为什么以及在哪里...

找到问题了!

我有这个:

zf = zipfile.ZipFile(path, mode='w')

然后我安装了zlib,把压缩改成了:

zf = zipfile.ZipFile(path, mode='w', compression=zipfile.ZIP_DEFLATED)

暂时没有...或任何类型的错误。 我想 Gmail 在某些情况下只是不喜欢 zipfile 模块的默认压缩。