Skip to content

Instantly share code, notes, and snippets.

@skylander86
Created January 4, 2017 18:10
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save skylander86/d75bf010c7685bd3f951d2b6c5a32e7b to your computer and use it in GitHub Desktop.
Python port of arithmetric/aws-lambda-ses-forwarder. An AWS Lambda function for forwarding incoming emails through SES.
"""
This code is a Python 2.7 port of [aws-lambda-ses-forwarder](https://github.com/arithmetric/aws-lambda-ses-forwarder). Follow instructions there for setting up SES and AWS Lambda.
"""
from email import message_from_file
import json
import logging
import os
import re
import boto3
from botocore.exceptions import ClientError
FORWARD_MAPPING = {
'source@example.com': ['email1@gmail.com', 'email2@gmail.com'],
}
VERIFIED_FROM_EMAIL = os.environ.get('VERIFIED_FROM_EMAIL', 'noreply@example.com') # An email that is verified by SES to use as From address.
SES_INCOMING_BUCKET = os.environ['SES_INCOMING_BUCKET'] # S3 bucket where SES stores incoming emails.
s3 = boto3.client('s3')
ses = boto3.client('ses')
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
def handle(event, context):
record = event['Records'][0]
assert record['eventSource'] == 'aws:ses'
o = s3.get_object(Bucket=SES_INCOMING_BUCKET, Key=record['ses']['mail']['messageId'])
raw_mail = o['Body']
msg = message_from_file(raw_mail)
del msg['DKIM-Signature']
del msg['Sender']
del msg['Return-Path']
original_from = msg['From']
del msg['From']
msg['From'] = re.sub(r'\<.+?\>', '', original_from).strip() + ' <{}>'.format(VERIFIED_FROM_EMAIL)
if not msg['Reply-To']: msg['Reply-To'] = original_from
msg['Return-Path'] = VERIFIED_FROM_EMAIL
msg_string = msg.as_string()
for recipient in record['ses']['receipt']['recipients']:
forwards = FORWARD_MAPPING.get(recipient, [])
if not forwards:
logger.warning('Recipent <{}> is not found in forwarding map. Skipping recipient.'.format(recipient))
continue
#end if
for address in forwards:
try:
o = ses.send_raw_email(Destinations=[address], RawMessage=dict(Data=msg_string))
logger.info('Forwarded email for <{}> to <{}>. SendRawEmail response={}'.format(recipient, address, json.dumps(o)))
except ClientError as e: logger.error('Client error while forwarding email for <{}> to <{}>: {}'.format(recipient, address, e))
#end for
#end for
#end def
@tedder
Copy link

tedder commented Jun 17, 2018

Here's my Python3 port and update:
https://github.com/tedder/aws_lambda_ses_forwarder_python3/blob/master/lambda-ses-forwarder-py3.py

Note I am assuming this py2.7 code is under the MIT license.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment