IMAP base64编码的PDF在保存时损坏

时间:2016-10-26 18:12:52

标签: python pdf base64 imap

我编写了一个脚本,可以从邮箱中的未读邮件中下载任何附件。 'application / pdf'内容类型我没有遇到任何麻烦。 base64编码'application / octet-stream'内容类型给了我一些时间。

我的代码将pdf移动到请求的路径,但损坏为0kb。任何帮助表示赞赏。

try:
    if part.get_content_type() == 'application/octet-stream':
        payload = part.get_payload(decode=1)
        fp = open(os.path.join('C:\\Attachment_Downloader\\',
                               datetime.datetime.now().strftime("%m%d%y%H%M%S")
                               + "_" + str(var_seq) + ".pdf"), 'wb')
        fp.write(base64.decodestring(payload))
        fp.close()
        logging.debug("File Decoded and Moved "+ part.get_filename())
except Exception as e:
    logging.debug("File Move Failed : " +  part.get_filename())
    logging.exception("message")

1 个答案:

答案 0 :(得分:0)

我正在解码两次。 我修改了我的代码到下面,它按预期工作:

try:
    if part.get_content_type() == 'application/octet-stream':
        payload = part.get_payload()
        fp = open(os.path.join('C:\\Attachment_Downloader\\',
                               datetime.datetime.now().strftime("%m%d%y%H%M%S")
                               + "_" + str(var_seq) + ".pdf"), 'wb')
        fp.write(base64.decodestring(payload))
        fp.close()
        logging.debug("File Decoded and Moved "+ part.get_filename())
except Exception as e:
    logging.debug("File Move Failed : " +  part.get_filename())
    logging.exception("message")