Last active
February 22, 2021 18:34
-
-
Save stenius/c6983f990bbbb1e49e4f to your computer and use it in GitHub Desktop.
AWS Lambda function for forwarding inbound emails from SES and sending outbound with SES
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import boto3 | |
import os | |
from __future__ import print_function | |
from email.parser import Parser | |
os.environ['AWS_DEFAULT_REGION'] = 'us-east-1' | |
# this is the email address you want the inbound mail forwarded to | |
FORWARD_ADDRESS = '' | |
# this is an email hosted on the domain with SES inbound | |
FROM_ADDRESS = '' | |
# fill in IAM access keys from AWS that have SES sending permission | |
client = boto3.client('ses', | |
aws_access_key_id='', | |
aws_secret_access_key='', | |
) | |
def decode_email(msg_str): | |
p = Parser() | |
message = p.parsestr(msg_str) | |
decoded_message = '' | |
for part in message.walk(): | |
charset = part.get_content_charset() | |
if part.get_content_type() == 'text/plain': | |
part_str = part.get_payload(decode=1) | |
decoded_message += part_str.decode(charset) | |
return decoded_message | |
def lambda_handler(event, context): | |
message = event['Records'][0]['Sns']['Message'] | |
message = json.loads(message) | |
body = decode_email(message['content']) | |
subject = message['mail']['commonHeaders']['subject'] | |
response = client.send_email( | |
Source=FROM_ADDRESS, | |
Destination={ | |
'ToAddresses': [ | |
FORWARD_ADDRESS, | |
], | |
}, | |
Message={ | |
'Subject': { | |
'Data': subject, | |
}, | |
'Body': { | |
'Text': { | |
'Data': body, | |
}, | |
'Html': { | |
'Data': body.replace("\n", "<br />"), | |
} | |
} | |
}, | |
) | |
return response |
@srikanth1239 There is a lot of other stuff that needs to be setup for SES. Can you post how you have that setup?
I could not have it work. Most probably because I chose SNS instead of some other things.
Here is my copy, updating yours: https://gist.github.com/dkavraal/356dc60f8f6beb8b5070e891adadab96
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello Stenius, I have used this program in Lambda, but this doesn't work at all.
-Srikanth