Skip to content

Instantly share code, notes, and snippets.

@elvisciotti
Created March 7, 2021 16:03
Show Gist options
  • Save elvisciotti/ea2d7552116fc14bd27bd91f08cb4656 to your computer and use it in GitHub Desktop.
Save elvisciotti/ea2d7552116fc14bd27bd91f08cb4656 to your computer and use it in GitHub Desktop.
Python handler to send a SES mail when a S3 object (with a ruleset mail) is created
# copiata pari pari da https://aws.amazon.com/blogs/messaging-and-targeting/forward-incoming-email-to-an-external-destination/
# https://docs.aws.amazon.com/lambda/latest/dg/with-s3.html
import os
import boto3
import email
import re
from botocore.exceptions import ClientError
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
region = os.environ['Region']
def get_message_from_s3(message_id):
incoming_email_bucket = os.environ['MailS3Bucket']
incoming_email_prefix = os.environ['MailS3Prefix']
if incoming_email_prefix:
object_path = (incoming_email_prefix + "/" + message_id)
else:
object_path = message_id
object_http_path = (f"http://s3.console.aws.amazon.com/s3/object/{incoming_email_bucket}/{object_path}?region={region}")
# Create a new S3 client.
client_s3 = boto3.client("s3")
# Get the email object from the S3 bucket.
object_s3 = client_s3.get_object(Bucket=incoming_email_bucket,
Key=object_path)
# Read the content of the message.
file = object_s3['Body'].read()
file_dict = {
"file": file,
"path": object_http_path
}
return file_dict
def create_message(file_dict):
sender = os.environ['MailSender']
recipient = os.environ['MailRecipient']
separator = ";"
# Parse the email body.
mailobject = email.message_from_string(file_dict['file'].decode('utf-8'))
# Create a new subject line.
subject_original = mailobject['Subject']
subject = "FW: " + subject_original
# The body text of the email.
body_text = ("The attached message was received from "
+ separator.join(mailobject.get_all('From'))
+ ". This message is archived at " + file_dict['path'])
# The file name to use for the attached message. Uses regex to remove all
# non-alphanumeric characters, and appends a file extension.
filename = re.sub('[^0-9a-zA-Z]+', '_', subject_original) + ".html"
# Create a MIME container.
msg = MIMEMultipart()
# Create a MIME text part.
text_part = MIMEText(body_text, _subtype="html")
# Attach the text part to the MIME message.
msg.attach(text_part)
# Add subject, from and to lines.
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipient
# Elvis aggiunto
msg['Body'] = body_text
# Create a new MIME object.
att = MIMEApplication(file_dict["file"], filename)
att.add_header("Content-Disposition", 'attachment', filename=filename)
# Attach the file object to the message.
msg.attach(att)
message = {
"Source": sender,
"Destinations": recipient,
"Data": msg.as_string()
}
print(message)
return message
def send_email(message):
aws_region = os.environ['Region']
# Create a new SES client.
client_ses = boto3.client('ses', region)
# Send the email.
try:
#Provide the contents of the email.
response = client_ses.send_raw_email(
Source=message['Source'],
Destinations=[
message['Destinations']
],
RawMessage={
'Data':message['Data']
}
)
# Display an error if something goes wrong.
except ClientError as e:
output = e.response['Error']['Message']
else:
output = "Email sent! Message ID: " + response['MessageId']
return output
def lambda_handler(event, context):
print(event)
# Get the unique ID of the message. This corresponds to the name of the file
# in S3.
# message_id = event['Records'][0]['ses']['mail']['messageId']
message_id = event['Records'][0]['s3']['object']['key']
print(f"Received message ID {message_id}")
# Retrieve the file from the S3 bucket.
file_dict = get_message_from_s3(message_id)
# Create the message.
message = create_message(file_dict)
# Send the email and print the result.
result = send_email(message)
print(result)
@elvisciotti
Copy link
Author

envs:

MailS3Bucket | The name of the S3 bucket
MailS3Prefix | The path of the folder in the S3 bucket where you will store incoming email.
MailSender | The email address that the forwarded message will be sent from. This address has to be verified.
MailRecipient | The address that you want to forward the message to.
Region | The name of the AWS Region that you want to use to send the email.

@elvisciotti
Copy link
Author

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