I am using Python and smtplib to send email via Amazon SES. How do I catch specific sending errors?
For example, Amazon SES may tell me “this address is blacklisted” or “you’ve exceeded your rate” or “you’ve exceeded your volume quota”, and I want to act on those messages.
I have a snippet which catches blacklisting (I think), as follows. I don’t really know how to debug these things, since the exceptions will only show up in heavy-duty environments, and if I trigger the exceptions then I’m worried Amazon will ding my quota.
try:
msg = EmailMultiAlternatives(subject, plain, from_address, [to_address])
msg.attach_alternative(html, "text/html")
msg.send()
except smtplib.SMTPResponseException as e:
error_code,error_msg = e.smtp_code, e.smtp_error
if error_code==554 and error_msg=='Message rejected: Address blacklisted.':
# do appropriate action for blacklisting
else:
# do appropriate action for throttling
else:
# log any other SMTP exceptions
You can use the Amazon SES Mailbox Simulator to generate a blacklist error.
Send an email to blacklist@simulator.amazonses.com to verify if your application handles the resulting error properly. Your bounce statistics will not be impacted if you use Mailbox Simulator addresses. You can run these tests whether your Amazon SES account is in Sandbox or Production mode.
The Mailbox Simulator does not currently let you test for throttling or quota exceptions. However, your exception handling code should be sufficient to handle those exceptions. I recommend you check for the exception string using
find()in order to accommodate any additions to the error message.For reference, here are some of the SMTP responses that you can check for: