Using AWS Python SDK to Read Simple Queue Service Messages

In this post, I want to share how to use AWS Simple Queue Service to manage email bounces and complaints. In my previous post, I wrote about sending emails using AWS Python SDK. First, we have to setup 2 SNS topics to handle email bounces and complaints. Go to the Simple Notification Service console and add a topic. After creating a SNS topic, you should see something similar to:

Pay attention to the protocol column above. The protocol for my email-bounce is set to SQS. This is very important since we want to process SQS messages every time SES receives a bounce or complaint. The endpoint is set to a SQS queue.

Now, let’s go back to the SES console and add a configuration set. Here is my SNS destination named email-bounces which is link to the email-bounce topic we created before.

During the sns setup, we also have to create a sqs queue to hold our messages.

Since SNS will be responsible to act as a proxy, we have to setup permissions for this queue to receive SNS messages.

After completing these steps, we are ready to read messages using Python.

I created a very simple Python script. At the top, I’m importing boto3 and my constructor is creating a sqsClient. To read messages, I created a method that takes an url as an argument. In line 24, you can see that the queueUrl is the location of our sqs email bounce. To actually read the message, we call receive_message and pass the sqs url and also MaxNumberOfMessages. In this case, I’m just using 1 to keep things simple. And finally we return the message.

I also have another method called GetEmailAddress that takes in a message as an argument. First, I retrieve the body string and start parsing it to find the email address. At the end of this method, I return the email address.

With this email address, I can clean up my records so I don’t send emails to it. That’s it for now. Next week, I’ll continue using Python scripts to interact with DynamoDB.