Files
notifications-api/app/clients/email/aws_ses.py
T

140 lines
4.1 KiB
Python
Raw Normal View History

2021-03-10 13:55:06 +00:00
from time import monotonic
2016-10-13 15:27:47 +01:00
import botocore
2023-01-31 17:27:17 -05:00
from boto3 import client
2016-03-02 09:33:20 +00:00
from flask import current_app
2016-10-13 15:27:47 +01:00
2023-08-10 18:02:45 -04:00
from app.clients import (
AWS_CLIENT_CONFIG,
STATISTICS_DELIVERED,
STATISTICS_FAILURE,
)
2021-03-10 13:55:06 +00:00
from app.clients.email import (
EmailClient,
EmailClientException,
EmailClientNonRetryableException,
)
2023-01-31 17:27:17 -05:00
from app.cloudfoundry_config import cloud_config
ses_response_map = {
'Permanent': {
"message": 'Hard bounced',
"success": False,
"notification_status": 'permanent-failure',
"notification_statistics_status": STATISTICS_FAILURE
},
'Temporary': {
"message": 'Soft bounced',
"success": False,
"notification_status": 'temporary-failure',
"notification_statistics_status": STATISTICS_FAILURE
},
'Delivery': {
"message": 'Delivered',
"success": True,
"notification_status": 'delivered',
"notification_statistics_status": STATISTICS_DELIVERED
},
'Complaint': {
"message": 'Complaint',
2016-04-08 16:13:10 +01:00
"success": True,
"notification_status": 'delivered',
"notification_statistics_status": STATISTICS_DELIVERED
}
}
def get_aws_responses(status):
return ses_response_map[status]
2016-03-10 17:29:17 +00:00
class AwsSesClientException(EmailClientException):
pass
class AwsSesClientThrottlingSendRateException(AwsSesClientException):
pass
class AwsSesClient(EmailClient):
'''
Amazon SES email client.
'''
2023-04-25 07:50:56 -07:00
def init_app(self, *args, **kwargs):
2023-01-31 17:27:17 -05:00
self._client = client(
'ses',
region_name=cloud_config.ses_region,
aws_access_key_id=cloud_config.ses_access_key,
2023-08-10 18:02:45 -04:00
aws_secret_access_key=cloud_config.ses_secret_key,
config=AWS_CLIENT_CONFIG
2023-01-31 17:27:17 -05:00
)
super(AwsSesClient, self).__init__(*args, **kwargs)
2016-02-25 11:23:04 +00:00
@property
def name(self):
return 'ses'
def send_email(self,
source,
to_addresses,
subject,
body,
2016-03-18 11:47:01 +00:00
html_body='',
2016-07-04 14:47:43 +01:00
reply_to_address=None):
try:
if isinstance(to_addresses, str):
to_addresses = [to_addresses]
2016-07-04 14:47:43 +01:00
reply_to_addresses = [reply_to_address] if reply_to_address else []
2016-03-18 11:47:01 +00:00
body = {
'Text': {'Data': body}
}
if html_body:
body.update({
'Html': {'Data': html_body}
})
2016-03-02 09:33:20 +00:00
start_time = monotonic()
response = self._client.send_email(
Source=source,
Destination={
2019-08-12 13:53:22 +01:00
'ToAddresses': [punycode_encode_email(addr) for addr in to_addresses],
'CcAddresses': [],
'BccAddresses': []
},
Message={
'Subject': {
'Data': subject,
},
2016-03-18 11:47:01 +00:00
'Body': body
},
2019-08-12 13:53:22 +01:00
ReplyToAddresses=[punycode_encode_email(addr) for addr in reply_to_addresses]
2016-10-13 14:17:17 +01:00
)
2016-10-13 15:27:47 +01:00
except botocore.exceptions.ClientError as e:
2016-10-13 16:07:32 +01:00
# http://docs.aws.amazon.com/ses/latest/DeveloperGuide/api-error-codes.html
2016-10-13 15:27:47 +01:00
if e.response['Error']['Code'] == 'InvalidParameterValue':
raise EmailClientNonRetryableException(e.response['Error']['Message'])
elif (
e.response['Error']['Code'] == 'Throttling'
and e.response['Error']['Message'] == 'Maximum sending rate exceeded.'
):
raise AwsSesClientThrottlingSendRateException(str(e))
2016-10-13 16:07:32 +01:00
else:
raise AwsSesClientException(str(e))
except Exception as e:
raise AwsSesClientException(str(e))
2016-10-13 15:27:47 +01:00
else:
elapsed_time = monotonic() - start_time
current_app.logger.info("AWS SES request finished in {}".format(elapsed_time))
return response['MessageId']
2019-08-12 13:53:22 +01:00
def punycode_encode_email(email_address):
# only the hostname should ever be punycode encoded.
local, hostname = email_address.split('@')
return '{}@{}'.format(local, hostname.encode('idna').decode('utf-8'))