File size: 1,459 Bytes
734560e
65bc4b3
 
734560e
 
 
65bc4b3
 
 
 
 
 
 
734560e
 
 
65bc4b3
 
734560e
 
65bc4b3
 
 
 
734560e
65bc4b3
734560e
 
 
 
 
65bc4b3
 
 
734560e
 
65bc4b3
734560e
65bc4b3
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# 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":     "no-reply@yourdomain.com"
            }
        })
        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}")