Last active
November 13, 2024 18:45
-
-
Save mkiser/f7d0614e11db27a9e3fe9321c3fdac37 to your computer and use it in GitHub Desktop.
A Python script for pulling MailChimp unsubscribe messages and saving as a CSV.
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 mailchimp_marketing as MailchimpMarketing | |
| from mailchimp_marketing.api_client import ApiClientError | |
| import csv | |
| import os | |
| try: | |
| client = MailchimpMarketing.Client() | |
| client.set_config({ | |
| "api_key": "XXX", | |
| "server": "XXX" | |
| }) | |
| lst = [] | |
| # Get X-number of campaign reports | |
| campaign_id = client.reports.get_all_campaign_reports(count=25) | |
| # Iterate over campaigns, grab IDs, request unsubscribe reports | |
| for id in campaign_id["reports"]: | |
| unsubs = client.reports.get_unsubscribed_list_for_campaign(id["id"], count=1000) | |
| reasons = unsubs["unsubscribes"] | |
| # Extract reasons for unsubscribe | |
| for unsub in reasons: | |
| if unsub["reason"].startswith(("None given", "No longer interested", "Spammy content", "Did not signup for list", "Inappropriate content")): | |
| pass | |
| else: | |
| lst.append([unsub["reason"]]) | |
| # Define file path to save CSV in the same directory as the script | |
| script_directory = os.path.dirname(__file__) | |
| file_path = os.path.join(script_directory, "unsubscribe_reasons.csv") | |
| # Write to CSV file | |
| with open(file_path, "w", newline="", encoding="utf-8") as csvfile: | |
| wr = csv.writer(csvfile, dialect='excel') | |
| wr.writerow(["Unsubscribe Reason"]) # Add header row | |
| wr.writerows(lst) # Write each reason in a new row | |
| print(f"Data written to {file_path}") | |
| except ApiClientError as error: | |
| print("Error: {}".format(error.text)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment