Skip to content

Instantly share code, notes, and snippets.

@coreindustries
Created December 27, 2019 18:26
Show Gist options
  • Save coreindustries/510a68d1c1928863f07602e3ff34d833 to your computer and use it in GitHub Desktop.
Save coreindustries/510a68d1c1928863f07602e3ff34d833 to your computer and use it in GitHub Desktop.
Python: send email via AWS SES
def send_email(subject="Website:", to="webmail@domain.com", body={'field': 'empty'}):
"""
GIVEN A SUBJECT, TO ADDRESS AND AN OBJECT,
SEND THE EMAIL VIA AWS SIMPLE EMAIL SERVICE
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ses.html
https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-using-sdk-python.html
"""
# FROM email address. A constant defined elsewhere
source_email = SOURCE_FROM_EMAIL
if 'IS_LOCAL' in os.environ and os.environ['IS_LOCAL']:
# TESTING LOCALLY
# will use credentials from ~/.aws/credentials.
session = boto3.Session(profile_name='some_profile')
else:
# we're running on Lambda, pull credentials automatically from assumed Role
session = boto3.Session()
client = session.client('ses', region_name=SES_AWS_REGION)
text_body, html_body = build_email_body(body)
log.debug(f"text email body: {text_body}")
try:
response = client.send_email(
Source=source_email,
Destination={
'ToAddresses': [
to
]
},
ReplyToAddresses=[
SOURCE_FROM_EMAIL
],
Message={
'Subject': {
'Data': subject,
'Charset': "UTF-8"
},
'Body': {
'Text': {
'Data': text_body,
'Charset': "UTF-8"
},
'Html': {
'Data': html_body,
'Charset': "UTF-8"
}
}
}
)
except ClientError as e:
log.warning(e.response['Error']['Message'])
return {"error": "There was a problem sending your email. Please wait a few seconds and try again"}
else:
log.info(f"Email sent! Message id: {response['MessageId']}")
log.info(response)
return {"OK": "Your email was successfully sent"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment