Skip to content

Instantly share code, notes, and snippets.

@alrafiabdullah
Created October 3, 2022 08:11
Show Gist options
  • Save alrafiabdullah/d507678a8ce7b22153e562fb1f8ddea0 to your computer and use it in GitHub Desktop.
Save alrafiabdullah/d507678a8ce7b22153e562fb1f8ddea0 to your computer and use it in GitHub Desktop.
Sending email using AWS SES and python.
import boto3
from botocore.exceptions import ClientError
def send_email_using_ses(email, name, subject, body):
"""Send an email using Amazon SES.
:param email: The recipient's email address.
:param subject: The subject of the email.
:param body: The body of the email.
:return: True if email was sent, otherwise False.
"""
# The HTML body of the email.
BODY_HTML = """<html>
<head></head>
<body>
<h1 style="color: blue;">Hi {name},</h1><br>
<h3>{body}</h3>
</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='ap-southeast-1')
# Try to send the email.
try:
# Provide the contents of the email.
response = client.send_email(
Destination={
'ToAddresses': [
email,
],
'BccAddresses': [
'email',
],
},
Message={
'Body': {
'Html': {
'Charset': CHARSET,
'Data': BODY_HTML.format(name=name, body=body),
},
'Text': {
'Charset': CHARSET,
'Data': body,
},
},
'Subject': {
'Charset': CHARSET,
'Data': subject,
},
},
Source='{} <{}>'.format(
'Sender Name', 'Sender Email'),
)
# Display an error if something goes wrong.
except ClientError as e:
print(e.response['Error']['Message'])
else:
print("Email sent! Message ID:"),
print(response['MessageId'])
return True
return False
if __name__ == "__main__":
send_email_using_ses("email", "name",
"subject", "body")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment