Search code examples
pythonboto3amazon-ses

download an image file from S3 and send as email in python using BytesIO and MIMEApplication results to zero bytes


I have this source to download a file from an S3 bucket where I uses BytesIO to store the read data in memory instead of file.

 with io.BytesIO() as img:
        img.name = 'screenshot.png'
        try:
            get_bucket().download_fileobj(key, img)
        except Exception as e:
            logger.error('ERROR processing screenshot, exception: %s',
                         str(e))
            raise NotFoundError()

and Sends the email thru this

            part = MIMEApplication(attachment.read())
            part.add_header('Content-Disposition', 'attachment',
                            filename=os.path.basename(attachment.name))
            msg.attach(part)

    _ses.send_raw_email(Source=sender, Destinations=recipients,
                        RawMessage={'Data': msg.as_string()})

where attachments is the img (BytesIO) object. My issue is when email is received, the bytes are 0, or the file is not visible.

DO you guys have any idea what is happening here or any hint on where to look for the issue?

by the way, the application is using a very old version of boto3 1.13.13. its an old system and we are just doing maintenance.


Solution

  • Try adding a img.seek(0) after download_fileobj.