| |
|
|
| import os |
| import mailchimp_marketing as MailchimpMarketing |
| from mailchimp_marketing.api_client import ApiClientError |
|
|
| |
| API_KEY = os.getenv("MAILCHIMP_API_KEY") |
| SERVER = os.getenv("MAILCHIMP_SERVER") |
| 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: |
| |
| 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"] |
|
|
| |
| client.campaigns.set_content(camp_id, {"html": html_content}) |
|
|
| |
| client.campaigns.send(camp_id) |
| return camp_id |
|
|
| except ApiClientError as e: |
| raise RuntimeError(f"Mailchimp error: {e.text}") |
|
|