Python Gmail API. socket.timeout - невозможно записать ошибку при попытке отправить файл .log - PullRequest
0 голосов
/ 17 июня 2020

Я перепробовал все возможные комбинации при отправке файла .log с помощью Python Gmail API. Однако, когда я пытаюсь создать сообщение электронной почты и отправить его как вложение, я получаю сообщение об ошибке socket.timeout, связанной с записью в сокет.

ошибка:

 File "C:\Users\MyUser\AppData\Local\Programs\Python\Python38-32\lib\http\client.py", line 1240, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "C:\Users\MyUser\AppData\Local\Programs\Python\Python38-32\lib\http\client.py", line 1286, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "C:\Users\MyUser\AppData\Local\Programs\Python\Python38-32\lib\http\client.py", line 1235, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "C:\Users\MyUser\AppData\Local\Programs\Python\Python38-32\lib\http\client.py", line 1045, in _send_output
    self.send(chunk)
  File "C:\Users\MyUser\AppData\Local\Programs\Python\Python38-32\lib\http\client.py", line 967, in send
    self.sock.sendall(data)
  File "C:\Users\MyUser\AppData\Local\Programs\Python\Python38-32\lib\ssl.py", line 1204, in sendall
    v = self.send(byte_view[count:])
  File "C:\Users\MyUser\AppData\Local\Programs\Python\Python38-32\lib\ssl.py", line 1173, in send
    return self._sslobj.write(data)
socket.timeout: The write operation timed out

Я использую эту функцию для создания электронного письма. Я возвращаю список из двух разных писем. Первое письмо - это письмо с вложениями. Второе письмо без вложений. Я отправляю электронное письмо без вложений, когда письмо с вложениями не удается.

Создать электронную почту:

 def createMessage(self, sender , to, subject, messageBody, attachmentList):
        try:
            message = MIMEMultipart()
            message['to'] = to
            message['from'] = sender
            message['subject'] = subject

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

            raw_message = base64.urlsafe_b64encode(message.as_string().encode("utf-8"))
            regularMessage = {'raw' : raw_message.decode("utf-8")}

            totalSizeOf = 0
            for targetAttachment in attachmentList:
                targetAttachmentExtension = targetAttachment.getFileExtension()
                if targetAttachmentExtension is False:
                    logging.error("Failed to get target attachment extension.")
                    continue
                targetAttachmentFileInstance = targetAttachment.getFileInstance()
                if targetAttachmentFileInstance is False:
                    logging.error("Failed to get file instance.")
                    continue
                attachmentSizeBytes = sys.getsizeof(targetAttachmentFileInstance)
                if totalSizeOf + attachmentSizeBytes > 5000000:
                    continue
                else:
                    totalSizeOf = totalSizeOf + attachmentSizeBytes
                if targetAttachmentExtension == 'jpg':
                    msgAttachment = MIMEImage(targetAttachmentFileInstance, _subtype='jpeg')
                elif targetAttachmentExtension == 'png':
                    msgAttachment = MIMEImage(targetAttachmentFileInstance, _subtype='png')
                elif targetAttachmentExtension == 'txt' or targetAttachmentExtension =='log':
                    if type(targetAttachmentFileInstance) is bytes:
                        targetAttachmentFileInstance = targetAttachmentFileInstance.decode('utf-8')
                    msgAttachment = MIMEText(targetAttachmentFileInstance, _subtype='plain')
                else:
                    msgAttachment = MIMEBase('application', 'octet-stream')
                    msgAttachment.set_payload(targetAttachmentFileInstance)
                targetAttachmentFileName = targetAttachment.getFullFilename()
                if targetAttachmentFileName is False:
                    logging.error("Failed to get attachment filename")
                    continue
                msgAttachment.add_header('Content-Disposition', 'attachment', filename=targetAttachmentFileName)
                message.attach(msgAttachment)
            raw = base64.urlsafe_b64encode(message.as_bytes())
            raw = raw.decode()
            attachmentMessage = {'raw' : raw}

            return [attachmentMessage, regularMessage]
        except:
            self.GLogger.error("An error was encountered while attempting create an email message")
            tb = traceback.format_exc()
            self.GLogger.exception(tb)
            return False

Функция отправки:

    def gmailAPISendEmailAttachmentFailover(self, message, userID="me"):
        try:
            service = self.gmailAPIService
            self.GLogger.info("Attempting to send email message")

            if type(message) != list:
                self.GLogger.error(f"Expected the message to be of type list")
                return False
            if len(message) != 2:
                self.GLogger.error("Message list length not 2")
                return False
            attachmentMessage = message[0]
            regularMessage = message[1]

            try:
                response = (service.users().messages().send(userId=userID, body=attachmentMessage).execute())
            except:
                response = (service.users().messages().send(userId=userID, body=regularMessage).execute())

            responseID = str(response['id'])
            self.GLogger.info("Successfully sent email message with ID (" + responseID +")")
            return responseID
        except:
            self.GLogger.error("Failed to send email message")
            tb = traceback.format_exc()
            self.GLogger.exception(tb)
            return False

Список вложений - это список объектов вложений. Единственное значение этого состоит в том, что я попытался прочитать файлы .log в объекте Attachment как «rb» и «r». Просто fileinstance = FID.read (). Я попытался отправить файл журнала как main_type = application и sub_type = octet-stream. Я также попытался отправить его как MIMEText с sub_type = plain. Как вы можете видеть в моей функции создания электронной почты, в настоящее время я также ограничиваю размер вложения до 5 МБ. Я уменьшил его с 15 МБ, так как думал, что это могло быть проблемой.

Я совсем в тупике, почему не работает. Пожалуйста помоги.

...