Skip to content

Instantly share code, notes, and snippets.

@zredlined
Created January 7, 2021 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zredlined/6b09af7d5d0996d43927fe7dcc33e3d9 to your computer and use it in GitHub Desktop.
Save zredlined/6b09af7d5d0996d43927fe7dcc33e3d9 to your computer and use it in GitHub Desktop.
Barebones AWS Lambda code to update a user's tags in Mailchimp
import json
import hashlib
import urllib3
API_KEY = "[API-KEY]"
DC = "us19"
LIST_ID = "[AUDIENCE]"
TAG = 'core'
http = urllib3.PoolManager()
def update_user(email):
hash = hashlib.md5(email.encode('utf-8')).hexdigest()
headers = urllib3.make_headers(basic_auth=f'foo:{API_KEY}')
encoded_data = json.dumps({"tags": [{"name": TAG, "status": "active"}]}).encode('utf-8')
r = http.request('POST',
f'https://{DC}.api.mailchimp.com/3.0/lists/{LIST_ID}/members/{hash}/tags',
body=encoded_data,
headers=headers)
return r.data.decode('utf-8')
def lambda_handler(event, context):
users = []
for rec in event['Records']:
# Assuming SNS Message = "email1, ..., emailN"
for email in rec['Sns']['Message'].split(','):
if len(email) > 0:
update_user(email.strip())
users.append(f"Added tag:{TAG} to user:{email}")
return {
'statusCode': 200,
'body': json.dumps(users)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment