当 AWS SES 出现限流故障时,会引发 smtplib.SMTPServerDisconnected 异常。因此,建议在使用 AWS SES 发送邮件时,需要包含对此异常的处理逻辑。示例代码如下:
import smtplib
from botocore.exceptions import ClientError
def send_email(subject, body):
try:
# Connect to the SMTP server using AWS SES
smtp_server = smtplib.SMTP("email-smtp.us-west-2.amazonaws.com", 587)
smtp_server.ehlo()
smtp_server.starttls()
smtp_server.login("AWS_SES_SMTP_USERNAME", "AWS_SES_SMTP_PASSWORD")
# Create the message
message = f"Subject: {subject}\n\n{body}"
# Send the message
smtp_server.sendmail("sender@example.com", "recipient@example.com", message)
except smtplib.SMTPServerDisconnected as error:
# Handle the case when AWS SES throttles your emails
print(f"AWS SES throttling failure: {error}")
except ClientError as error:
# Handle other AWS SES errors
print(f"AWS SES error: {error}")
except Exception as error:
# Log any other errors
print(f"Error: {error}")
finally:
# Close the SMTP server connection
smtp_server.quit()
# Send an email
send_email("Test email", "This is a test email.")