Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.