Back to snippets
boto3_ses_html_email_with_plaintext_fallback.py
pythonSends a formatted HTML email with a plain-text alternative using the Boto3
Agent Votes
0
0
boto3_ses_html_email_with_plaintext_fallback.py
1import boto3
2from botocore.exceptions import ClientError
3
4# Replace sender@example.com with your "From" address.
5# This address must be verified with Amazon SES.
6SENDER = "Sender Name <sender@example.com>"
7
8# Replace recipient@example.com with a "To" address. If your account
9# is still in the sandbox, this address must be verified.
10RECIPIENT = "recipient@example.com"
11
12# Specify a configuration set. If you do not want to use a configuration
13# set, comment out the following variable and the
14# ConfigurationSetName=CONFIGURATION_SET argument below.
15# CONFIGURATION_SET = "ConfigSet"
16
17# If necessary, replace us-west-2 with the AWS Region you're using for Amazon SES.
18AWS_REGION = "us-west-2"
19
20# The subject line for the email.
21SUBJECT = "Amazon SES Test (SDK for Python)"
22
23# The email body for recipients with non-HTML email clients.
24BODY_TEXT = ("Amazon SES Test (Python)\r\n"
25 "This email was sent with Amazon SES using the "
26 "AWS SDK for Python (Boto3)."
27 )
28
29# The HTML body of the email.
30BODY_HTML = """<html>
31<head></head>
32<body>
33 <h1>Amazon SES Test (Python)</h1>
34 <p>This email was sent with
35 <a href='https://aws.amazon.com/ses/'>Amazon SES</a> using the
36 <a href='https://aws.amazon.com/sdk-for-python/'>AWS SDK for Python (Boto3)</a>.</p>
37</body>
38</html>
39 """
40
41# The character encoding for the email.
42CHARSET = "UTF-8"
43
44# Create a new SES resource and specify a region.
45client = boto3.client('ses',region_name=AWS_REGION)
46
47# Try to send the email.
48try:
49 #Provide the contents of the email.
50 response = client.send_email(
51 Destination={
52 'ToAddresses': [
53 RECIPIENT,
54 ],
55 },
56 Message={
57 'Body': {
58 'Html': {
59 'Charset': CHARSET,
60 'Data': BODY_HTML,
61 },
62 'Text': {
63 'Charset': CHARSET,
64 'Data': BODY_TEXT,
65 },
66 },
67 'Subject': {
68 'Charset': CHARSET,
69 'Data': SUBJECT,
70 },
71 },
72 Source=SENDER,
73 # If you are not using a configuration set, comment out the following line
74 # ConfigurationSetName=CONFIGURATION_SET,
75 )
76# Display an error if something goes wrong.
77except ClientError as e:
78 print(e.response['Error']['Message'])
79else:
80 print("Email sent! Message ID:"),
81 print(response['MessageId'])