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.")
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.
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.
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.
You can download the attachment to /tmp directory in Lambda and then upload to S3.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With