Encapsulates functions to send emails with Amazon SES.
| 52 | |
| 53 | # snippet-start:[python.example_code.ses.SesMailSender] |
| 54 | class SesMailSender: |
| 55 | """Encapsulates functions to send emails with Amazon SES.""" |
| 56 | |
| 57 | def __init__(self, ses_client): |
| 58 | """ |
| 59 | :param ses_client: A Boto3 Amazon SES client. |
| 60 | """ |
| 61 | self.ses_client = ses_client |
| 62 | |
| 63 | # snippet-end:[python.example_code.ses.SesMailSender] |
| 64 | |
| 65 | # snippet-start:[python.example_code.ses.SendEmail] |
| 66 | def send_email(self, source, destination, subject, text, html, reply_tos=None): |
| 67 | """ |
| 68 | Sends an email. |
| 69 | |
| 70 | Note: If your account is in the Amazon SES sandbox, the source and |
| 71 | destination email accounts must both be verified. |
| 72 | |
| 73 | :param source: The source email account. |
| 74 | :param destination: The destination email account. |
| 75 | :param subject: The subject of the email. |
| 76 | :param text: The plain text version of the body of the email. |
| 77 | :param html: The HTML version of the body of the email. |
| 78 | :param reply_tos: Email accounts that will receive a reply if the recipient |
| 79 | replies to the message. |
| 80 | :return: The ID of the message, assigned by Amazon SES. |
| 81 | """ |
| 82 | send_args = { |
| 83 | "Source": source, |
| 84 | "Destination": destination.to_service_format(), |
| 85 | "Message": { |
| 86 | "Subject": {"Data": subject}, |
| 87 | "Body": {"Text": {"Data": text}, "Html": {"Data": html}}, |
| 88 | }, |
| 89 | } |
| 90 | if reply_tos is not None: |
| 91 | send_args["ReplyToAddresses"] = reply_tos |
| 92 | try: |
| 93 | response = self.ses_client.send_email(**send_args) |
| 94 | message_id = response["MessageId"] |
| 95 | logger.info( |
| 96 | "Sent mail %s from %s to %s.", message_id, source, destination.tos |
| 97 | ) |
| 98 | except ClientError: |
| 99 | logger.exception( |
| 100 | "Couldn't send mail from %s to %s.", source, destination.tos |
| 101 | ) |
| 102 | raise |
| 103 | else: |
| 104 | return message_id |
| 105 | |
| 106 | # snippet-end:[python.example_code.ses.SendEmail] |
| 107 | |
| 108 | # snippet-start:[python.example_code.ses.SendTemplatedEmail] |
| 109 | def send_templated_email( |
| 110 | self, source, destination, template_name, template_data, reply_tos=None |
| 111 | ): |
no outgoing calls