gpt4 book ai didi

python - 从 AWS SES 中的 content-type=application/zip 和 base64 编码解析文本文件

转载 作者:太空宇宙 更新时间:2023-11-03 15:23:54 24 4
gpt4 key购买 nike

在亚马逊 SES 上,我有一条规则将传入电子邮件保存到 S3 存储桶。亚马逊以 MIME 格式保存这些内容。

这些电子邮件的附件中包含 .txt,该附件将在 MIME 文件中显示为 content-type=text/plainContent-Disposition=attachment ....txtContent-Transfer-Encoding=quoted-printablebases64

我能够使用 python 很好地解析它。

.txt 文件附件被压缩时(即 content-type: applcation/zip),我在解码该附件的内容时遇到问题,就好像编码一样不是 base64

我的代码:

import base64
s = unicode(base64.b64decode(attachment_content), "utf-8")

抛出错误:

Traceback (most recent call last):
File "<input>", line 796, in <module>
UnicodeDecodeError: 'utf8' codec can't decode byte 0xcf in position 10: invalid continuation byte

下面是attachment_content中“base64”字符串的前几行,顺便说一句,最后的长度为53683 +“==”,我认为base64的长度应该是4 的倍数 (??)。因此,解码可能会失败,因为压缩正在更改 attachment_content 并且我在解码之前/之后需要一些其他操作?我真的不知道..

UEsDBBQAAAAIAM9Ah0otgkpwx5oAADMTAgAJAAAAX2NoYXQudHh0tL3bjiRJkiX23sD+g0U3iOxu
REWGu8c1l2Ag8lKd0V2ZWajM3kLuC6Hubu5uFeZm3nYJL6+n4T4Ry8EOdwCSMyQXBRBLgMQ+7CP5
QPBj5gdYn0CRI6JqFxWv7hlyszursiJV1G6qonI5cmQyeT6dPp9cnCaT6Yvp5Yvz6xfJe7cp8P/k
1SbL8xfJu0OSvUvr2q3TOnFVWjxrknWZFeuk2VRlu978s19MRvNMrHneOv51SOZlGUtMLYnfp0nd

...

我也尝试过使用“latin-1”,但是得到了乱码。

最佳答案

问题是,转换后,我正在处理格式为“PK\x03\x04\X3C\Xa\x0c ...”的压缩文件,我需要在将其转换为 UTF-8 unicode 之前解压缩。

这段代码对我有用:

import email

# Parse results from email
received_email = email.message_from_string(email_text)
for part in received_email.walk():
c_type = part.get_content_type()
c_enco = part.get('Content-Transfer-Encoding')

attachment_content = part.get_payload()

if c_enco == 'base64':
import base64
decoded_file = base64.b64decode(attachment_content)
print("File decoded from base64")

if c_type == "application/zip":
from cStringIO import StringIO
import zipfile
zfp = zipfile.ZipFile(StringIO(decoded_file), "r")
unzipped_list = zfp.open(zfp.namelist()[0]).readlines()
decoded_file = "".join(unzipped_list)
print('And un-zipped')

result = unicode(decoded_file, "utf-8")

关于python - 从 AWS SES 中的 content-type=application/zip 和 base64 编码解析文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43287670/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com