Skip to content

Instantly share code, notes, and snippets.

@kuharan
Created February 14, 2021 05:35
Show Gist options
  • Save kuharan/9235f6611f6c3cf05572a549964ec8b8 to your computer and use it in GitHub Desktop.
Save kuharan/9235f6611f6c3cf05572a549964ec8b8 to your computer and use it in GitHub Desktop.
Send emails in AWSlambda
from botocore.exceptions import ClientError
from botocore.vendored import requests
def send_email(sender, recipient, aws_region, subject):
# This address must be verified with Amazon SES.
SENDER = sender
# If your account is still in the sandbox, this address must be verified.
RECIPIENT = recipient
# Specify a configuration set. If you do not want to use a configuration
# set, comment the following variable, and the
# ConfigurationSetName=CONFIGURATION_SET argument below.
# CONFIGURATION_SET = "ConfigSet"
# The AWS Region you're using for Amazon SES.
AWS_REGION = aws_region
# The subject line for the email.
SUBJECT = subject
# The email body for recipients with non-HTML email clients.
BODY_TEXT = "..."
# The HTML body of the email.
BODY_HTML = """<html> <head></head> <body> <h1>Amazon SES Test (SDK for Python)</h1> <p>This email was sent with <a href='https://aws.amazon.com/ses/'> Amazon SES </a> using <a href='https://aws.amazon.com/sdk-for-python/'> AWS SDK for Python (Boto)</a>.</p> </body> </html>"""
# The character encoding for the email.
CHARSET = "UTF-8"
# Create a new SES resource and specify a region.
client = boto3.client('ses',region_name=AWS_REGION)
# Try to send the email.
try:
#Provide the contents of the email.
response = client.send_email(
Destination={
'ToAddresses': [
RECIPIENT,
],
},
Message={
'Body': {
'Html': {
'Charset': CHARSET,
'Data': BODY_HTML,
},
'Text': {
'Charset': CHARSET,
'Data': BODY_TEXT,
},
},
'Subject': {
'Charset': CHARSET,
'Data': SUBJECT,
},
},
Source=SENDER,
# If you are not using a configuration set, comment or delete the
# following line
# ConfigurationSetName=CONFIGURATION_SET,
)
# Display an error if something goes wrong.
except ClientError as e:
return(e.response['Error']['Message'])
else:
return("Email sent! Message ID:" + response['MessageId'] )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment