# mailchimp_client.py | |
import os | |
import mailchimp_marketing as MailchimpMarketing | |
from mailchimp_marketing.api_client import ApiClientError | |
# Read credentials from env (set these in HF Space Settings β Secrets) | |
API_KEY = os.getenv("MAILCHIMP_API_KEY") | |
SERVER = os.getenv("MAILCHIMP_SERVER") # e.g. "us19" | |
LIST_ID = os.getenv("MAILCHIMP_LIST_ID") | |
if not all([API_KEY, SERVER, LIST_ID]): | |
raise ValueError("Missing one of MAILCHIMP_API_KEY, MAILCHIMP_SERVER, or MAILCHIMP_LIST_ID") | |
client = MailchimpMarketing.Client() | |
client.set_config({ | |
"api_key": API_KEY, | |
"server": SERVER | |
}) | |
def create_and_send_campaign(subject: str, html_content: str): | |
""" | |
Create a Mailchimp campaign and send it immediately. | |
""" | |
try: | |
# 1. Create campaign | |
campaign = client.campaigns.create({ | |
"type": "regular", | |
"recipients": {"list_id": LIST_ID}, | |
"settings": { | |
"subject_line": subject, | |
"title": subject, | |
"from_name": "AutoExec AI", | |
"reply_to": "[email protected]" | |
} | |
}) | |
camp_id = campaign["id"] | |
# 2. Set campaign content | |
client.campaigns.set_content(camp_id, {"html": html_content}) | |
# 3. Send campaign | |
client.campaigns.send(camp_id) | |
return camp_id | |
except ApiClientError as e: | |
raise RuntimeError(f"Mailchimp error: {e.text}") | |