Amazon SES 提供了批量发送模板邮件 API 的功能,但是在使用过程中需要考虑相应的配额问题。SEND_BULK_TEMPLATED_EMAIL 操作每秒可以发送的邮件数量是受限的,而配额数量因 AWS 账户类型而异。如果超过了您的配额,您会收到类似以下的错误响应:
{
"Error": {
"Code": "Throttling",
"Message": "Rate exceeded",
"Type": "Sender"
},
"RequestId": "e0d13728-5422-11e8-b8a9-63637c3edd1b"
}
解决该问题的方法是,通过使用 Amazon SES 提供的 DescribeAccountAttributes API 获取账户的该操作的配额信息,然后根据配额信息来控制邮件发送速度以避免超配额。
以下是一个示例代码,展示了如何使用 DescribeAccountAttributes API 获取配额并控制发送速度:
import time
import boto3
client = boto3.client('ses')
response = client.describe_account_attributes(
AttributeNames=[
'max_send_rate'
]
)
max_send_rate = int(float(response['AccountAttributes'][0]['AttributeValues'][0]['Value']))
send_rate = min(max_send_rate, 14) # 控制发送速度
for dest in destinations:
client.send_bulk_templated_email(
Source=source,
Template=template_name,
Destinations=[
{
'Destination': {
'ToAddresses': [dest]
},
'ReplacementTemplateData': template_data[dest]
}
]
)
time.sleep(1/send_rate) # 控制发送速度
在此示例代码中,我们通过调用 DescribeAccountAttributes API 来获取账户的 max_send_rate
属性。接下来,我们计算本次发送的速率并遍历要发送的每个收件人,控制发送速度。若当前配额较小,则我们会将发送速率设置为 14 条/秒。
为了保证不超出配额,我们通过使用 time.sleep()
函数来限制发送速度。在该函数中,参数为发送速率的倒数。例如,在本示例中,若当前发送速率为 7 条/秒,则 time.sleep()
函数的参数为 1/7(约 0.14)秒。