在 AWS Lambda 上使用 Python 从 S3 中的 AWS SES 邮件中提取电子邮件附件

问题描述

我想在 AWS 上构建一个基本的电子邮件附件处理器。 我按照这个示例 (https://medium.com/caspertechteam/processing-email-attachments-with-aws-a35a1411a0c4),让 AWS 上的所有内容相互通信(SES、S3、Lambda)。

我可以阅读普通电子邮件内容(仅限文本)。现在,我切换到带有附件的消息。 我有这个代码(在 AWS Lambda,Python 3.8 中)

import boto3
import email 

def lambda_handler(event,context):
    s3 = boto3.resource('s3')
    
    bucket = 'myBucket'
    key = 'inbound/cl2kjuud8oaqm6ihac491hs5s404krv6nkpq7781' # with csv attachment
    # key = 'inbound/kvqlcdlaqaqhq8i5a3m51nsr8ehehhsl227hu881' # no att
    
    obj = s3.Bucket(bucket).Object(key)
    body = obj.get()["Body"].read().decode('utf-8') # decode necessary,or error message
    
    msg = email.message_from_string(body)
    
    attachment = get_attachment(msg,'text/plain')
    
# this code is copy&paste from tutorial above
def get_attachment(msg,content_type):
    """
    Moves through a tree of email Messages to find an attachment.
    :param msg: An email Message object containing an attachment in its Message tree
    :param content_type: The type of attachment that is being searched for
    :return: An email Message object containing base64 encoded contents (i.e. the attachment)
    """
    attachment = None
    msg_content_type = msg.get_content_type()

    if ((msg_content_type == content_type or msg_content_type == 'text/plain')
            and is_base64(msg.get_payload())):
        attachment = msg

    elif msg_content_type.startswith('multipart/'):
        for part in msg.get_payload():
            attachment = get_attachment(part,content_type)
            attachment_content_type = attachment.get_content_type()

            if (attachment and (attachment_content_type == content_type
                                or attachment_content_type == 'text/plain')
                    and is_base64(attachment.get_payload())):
                break
            else:
                attachment = None

    return attachment

我收到此错误

Response:
{
  "errorMessage": "'nonetype' object has no attribute 'get_content_type'","errorType": "AttributeError","stackTrace": [
    "  File \"/var/task/lambda_function.py\",line 24,in lambda_handler\n    attachment = get_attachment(msg,'text/plain')\n","  File \"/var/task/lambda_function.py\",line 58,in get_attachment\n    attachment_content_type = attachment.get_content_type()\n"
  ]
}

我用 Python 2.8 运行时试过,用 message_from_bytes() 试过,似乎没有任何效果。 现在我被困住了。 你能分享一些建议吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)