Extract and save attachment from email (via SES) i

2020-03-19 02:48发布

I want to extract the attachment from email and save it into my new S3 bucket. So far, I have configured AWS Simple Email Service to intercept incoming emails. Now I have an AWS lambda python function, which gets triggered on S3 Put.

Until this it is working. But my lambda is giving error saying: "[Errno 2] No such file or directory: 'abc.docx': OSError". I see that the attachment with the name abc.docx is mentioned in the raw email in S3.

I assume the problem is in my upload_file. Could you please help me here.

Please find below the relevant parts of my code.

s3 = boto3.client('s3')
s3resource = boto3.resource('s3')


waiterFlg = s3.get_waiter('object_exists')
waiterFlg.wait(Bucket=bucket, Key=key)

response = s3resource.Bucket(bucket).Object(key)

message = email.message_from_string(response.get()["Body"].read())

    if len(message.get_payload()) == 2:

        attachment = msg.get_payload()[1]
        s3resource.meta.client.upload_file(attachment.get_filename(), outputBucket, attachment.get_filename())

    else:
        print("Could not see file/attachment.")

2条回答
做自己的国王
2楼-- · 2020-03-19 03:28

The following code solved the issue.

open('/tmp/newFile.docx', 'wb').write(attachment.get_payload(decode=True)) s3r.meta.client.upload_file('/tmp/newFile.docx', outputBucket, attachment.get_filename())

查看更多
不美不萌又怎样
3楼-- · 2020-03-19 03:48

You can download the attachment to /tmp directory in Lambda and then upload to S3.

查看更多
登录 后发表回答