title: Using Lambda function to parse SES email with attachment and send to S3 bucket
body: <p><strong>SITUATION:</strong> I verified a domain name in AWS and set up an S3 bucket that recieves emails.
  These emails contain a .csv file and are delivered to this bucket on a daily basis. I can verify the presence of the attachment by manually exploring the raw email. No problems.</p>
  <p><strong>DESIRED OUTCOME:</strong> I want to parse these emails, extract the attached .csv and send the .csv file to a destination S3 bucket (or destination folder within the same S3 bucket) so that I can later process it using a seperate Python script</p>
  <p><strong>ISSUE:</strong> I have written the Lambda function in Python and the logs show this executes successfully when testing yet no files appear in the destination folder.</p>
  <p>There is an <code>ObjectCreated</code> trigger enabled on the source bucket which I believe should activate the function on arrival of a new email but this does not have any effect on the execution of the function.</p>
  <p>See Lambda function code below:</p>
  <pre><code>
  import json
  import urllib
  import boto3
  import os
  
  import email
  import base64
  
  FILE_MIMETYPE = 'text/csv'
  
  # destination folder
  S3_OUTPUT_BUCKETNAME = 's3-bucketname/folder' 
  
  print('Loading function')
  
  s3 = boto3.client('s3')
  
  
  def lambda_handler(event, context):
  
      #source email bucket 
      inBucket = event['Records'][0]['s3']['bucket']['name']
      key = urllib.parse.quote(event['Records'][0]['s3']['object']['key'].encode('utf8'))
  
  
      try:
          response = s3.get_object(Bucket=inBucket, Key=key)
          msg = email.message_from_string(response['Body'].read().decode('utf-8'))   
  
      except Exception as e:
          print(e)
          print('Error retrieving object {} from source bucket {}. Verify existence and ensure bucket is in same region as function.'.format(key, inBucket))
          raise e
          
      attachment_list = []
  
      try:
          #scan each part of email 
          for message in msg.get_payload():
              
              # Check filename and email MIME type
              if (msg.get_filename() != None and msg.get_content_type() == FILE_MIMETYPE):
                  attachment_list.append ({'original_msg_key':key, 'attachment_filename':msg.get_filename(), 'body': base64.b64decode(message.get_payload()) })
      except Exception as e:
          print(e)
          print ('Error processing email for CSV attachments')
          raise e
      
      # if multiple attachments send all to bucket 
      for attachment in attachment_list:
  
          try:
              s3.put_object(Bucket=S3_OUTPUT_BUCKETNAME, Key=attachment['original_msg_key'] +'-'+attachment['attachment_filename'] , Body=attachment['body']) 
          except Exception as e:
              print(e)
              print ('Error sending object {} to destination bucket {}. Verify existence and ensure bucket is in same region as function.'.format(attachment['attachment_filename'], S3_OUTPUT_BUCKETNAME))
              raise e
          
      return event
  </code></pre>
  <p>Unfamiliar territory so please let me know if further information is required.</p>
  <p><strong>EDIT</strong>
  As per comments I have checked the logs. Seems that function is being invoked but the attachment is not being parsed and sent to destination folder. It's possible that there's an error in the Python file itself.</p>
  <p><a href="https://i.stack.imgur.com/8P1T6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8P1T6.png" alt="enter image description here" /></a></p>