Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract and save attachment from email (via SES) into AWS S3

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.")
like image 812
user3567195 Avatar asked Jun 06 '17 12:06

user3567195


People also ask

Can you email a file to an S3 bucket?

You can send attachments in your emails, which will get saved in the S3 bucket you specify. You'll need to connect an AWS account (access and secret key) to the save_to_s3 step. The user tied to these keys should have PutObject permissions on the target bucket.

How do I send attachments with SES?

File attachments To attach a file to an email, you have to encode the attachment using base64 encoding. Attachments are typically placed in dedicated MIME message parts, which include the following headers: Content-Type: The file type of the attachment.

Can SNS send email with attachment?

No, it can't. The SNS FAQ does not come out and explain this explicitly, but it can be inferred from several statements: Amazon SNS messages can contain up to 256 KB of text data, including XML, JSON and unformatted text.


2 Answers

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

like image 102
Ashan Avatar answered Nov 05 '22 18:11

Ashan


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())

like image 38
user3567195 Avatar answered Nov 05 '22 18:11

user3567195