skip to Main Content

I have an SNS topic to which a lambda is sending messages. The specific message contains the email address to which this message should be sent from SNS. Can I create an email topic subscriber in a way that the endpoint (email address) is determined at runtime from the message itself (either message attributes or message body)?

I think this calls for involvement of SES. But, would like to take the simpler SNS route.

2

Answers


  1. Unfortunately, SNS does not allow dynamic creation of topic subscribers or dynamically setting the endpoint (email address) from the message body or attributes. When you subscribe an email endpoint to an SNS topic, the endpoint must be statically defined during the subscription process.

    but what you can do, is creating different SNSs, with a specific users for each, and then you dynamically choose which SNS you want to forward the message to. but this requires a mapping between users (or email addresses) and SNS topics.

    with SES it’s possible, so you can create a lambda as an SNS subscriber and it will take the message and do all the work. this is an example of how it may be done:

    def lambda_handler(event, context):
        ses_client = boto3.client('ses')
        
        for record in event['Records']:
            sns_message = json.loads(record['Sns']['Message'])
            email_address = sns_message.get('email')  
            message_body = sns_message.get('body', 'Default body text')
    
            response = ses_client.send_email(
                Source='[email protected]',
                Destination={
                    'ToAddresses': [email_address]
                },
                Message={
                    'Subject': {
                        'Data': 'Dynamic Email Subject'
                    },
                    'Body': {
                        'Text': {
                            'Data': message_body
                        }
                    }
                }
            )
        return {'statusCode': 200, 'body': 'Email sent successfully'}
    
    Login or Signup to reply.
  2. Check out my project where we used SNS to send emails and dynamically created topics. The code is a bit messy but it’s honest work—Github Netflix-like serverless AWS app.

    • The file I linked is a file where we used notified. There are also .py scripts that subscribe to those topics dynamically.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search