【问题标题】:Need help with processing attachments with GAE InboundMailHandler在使用 AGE InboundeMailHandler 处理附件方面需要帮助
【发布时间】:2011-08-04 22:27:22
【问题描述】:

我已经正确实现了 InboundMailHandler,并且能够处理除 mail_message.attachments 之外的所有其他 mail_message 字段。附件文件名被正确读取,但内容未保存在正确的 mime_type 中

        if not hasattr(mail_message, 'attachments'):
            raise ProcessingFailedError('Email had no attached documents')

        else:
            logging.info("Email has %i attachment(s) " % len(mail_message.attachments))

        for attach in mail_message.attachments:
            filename = attach[0]
            contents = attach[1]


        # Create the file
        file_name = files.blobstore.create(mime_type = "application/pdf")

        # Open the file and write to it
        with files.open(file_name, 'a') as f:
            f.write(contents)

        # Finalize the file. Do this before attempting to read it.
        files.finalize(file_name)

        # Get the file's blob key
        blob_key = files.blobstore.get_blob_key(file_name)
        return blob_key

        blob_info = blobstore.BlobInfo.get(blob_key)

`

当我尝试通过转到 url 来显示导入的 pdf 文件时:'/serve/%s' % blob_info.key() 我得到一个看起来像是编码数据的页面,而不是实际的 pdf 文件。

看起来像这样:

From nobody Thu Aug 4 23:45:06 2011 content-transfer-encoding: base64 JVBERi0xLjMKJcTl8uXrp/Og0MTGCjQgMCBvYmoKPDwgL0xlbmd0aCA1IDAgUiAvRmlsdGVyIC9G bGF0ZURlY29kZSA+PgpzdHJlYW0KeAGtXVuXHLdxfu9fgSef2RxxOX2by6NMbSLalOyQK+ucyHpQ eDE3IkWKF0vJj81vyVf3Qu9Mdy+Z40TswqKAalThqwJQjfm1/Hv5tWzxv13blf2xK++el+/LL+X+ g/dtefq

有什么想法吗?谢谢

【问题讨论】:

    标签: google-app-engine email blobstore


    【解决方案1】:

    电子邮件的附件是EncodedPayload 对象;要获取数据,您应该调用decode() 方法。

    尝试:

    # Open the file and write to it
    with files.open(file_name, 'a') as f:
        f.write(contents.decode())
    

    【讨论】:

      【解决方案2】:

      如果你想成功处理大于1MB的附件,解码并转换为str:

      #decode and convert to string
      datastr = str(contents.decode())
      with files.open(file_name, 'a') as f:
        f.write(datastr[0:65536])
        datastr=datastr[65536:]
        while len(datastr) > 0:
          f.write(datastr[0:65536])
          datastr=datastr[65536:]
      

      【讨论】:

        【解决方案3】:

        在这篇出色的 Blob 帖子中找到了答案: http://john-smith.appspot.com/app-engine--what-the-docs-dont-tell-you-about-processing-inbound-mail

        这是解码 GAE 入站邮件的电子邮件附件的方法:

                for attach in mail_message.attachments:
                    filename, encoded_data = attach
                    data = encoded_data.payload
                    if encoded_data.encoding:
                        data = data.decode(encoded_data.encoding)
        

        【讨论】:

        • Afaik if encoded_data.encoding 检查没用,decode 方法在内部执行 exactly the same
        猜你喜欢
        • 1970-01-01
        • 2019-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-13
        • 2018-01-11
        • 1970-01-01
        相关资源
        最近更新 更多