Last active
December 16, 2020 01:07
-
-
Save alecbw/834028b5370ff72cb57dc6b6ce5f3bc6 to your computer and use it in GitHub Desktop.
MailChimp Modify User's Tag (add, update, deactivate) - The Python implementation that doesn't use their SDK
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import hashlib | |
import requests | |
import os | |
import json | |
""" | |
Docs: https://mailchimp.com/developer/guides/organize-contacts-with-tags/#label-a-contact-with-a-tag | |
Emails must be MD5 hashed before sending the call (such is done so below) | |
The API returns 204 No Content no matter if the input is valid or invalid | |
This means it will fail silently (e.g. if the value for data is not a valid JSON string) | |
""" | |
def add_tag_to_user(email, tag): | |
AUDIENCE_ID = os.environ["AUDIENCE_ID"] | |
SUBSCRIBER_HASH = hashlib.md5(email.encode('utf-8')).hexdigest() | |
request_kwargs = { | |
"headers": { | |
"Authorization": "Bearer " + os.environ["MC_KEY"], | |
"Content-Type": "application/json" # technically not necessary to add | |
}, | |
"data": json.dumps({"tags": [{"name": tag, "status": "active"}]}) | |
} | |
endpoint = f"https://us4.api.mailchimp.com/3.0/lists/{AUDIENCE_ID}/members/{SUBSCRIBER_HASH}/tags" | |
resp = requests.post(endpoint, **request_kwargs) | |
add_tag_to_user("[email protected]", "Example Tag Name") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment