import os, requests, time
MC_KEY = os.environ["MAILCHIMP_API_KEY"]
MC_DC = os.environ["MAILCHIMP_DC"]
MV = os.environ["MAVERA_API_KEY"]
MB = "https://app.mavera.io/api/v1"
MH = {"Authorization": f"Bearer {MV}", "Content-Type": "application/json"}
MC_BASE = f"https://{MC_DC}.api.mailchimp.com/3.0"
mc_auth = ("anystring", MC_KEY)
r = requests.get(
f"{MC_BASE}/campaigns",
auth=mc_auth,
params={
"count": 50,
"sort_field": "send_time",
"sort_dir": "DESC",
"status": "sent",
"fields": "campaigns.id,campaigns.settings,campaigns.report_summary,campaigns.send_time",
},
)
r.raise_for_status()
campaigns = r.json().get("campaigns", [])
scored = []
for c in campaigns:
report = c.get("report_summary", {})
opens = report.get("open_rate", 0)
clicks = report.get("click_rate", 0)
settings = c.get("settings", {})
if opens > 0:
scored.append({
"id": c["id"],
"subject": settings.get("subject_line", ""),
"preview": settings.get("preview_text", ""),
"from_name": settings.get("from_name", ""),
"open_rate": opens,
"click_rate": clicks,
"send_time": c.get("send_time", ""),
})
scored.sort(key=lambda x: x["open_rate"] * 0.6 + x["click_rate"] * 0.4, reverse=True)
top = scored[:15]
bottom = scored[-5:]
winning_content = []
for camp in top[:10]:
report_r = requests.get(f"{MC_BASE}/reports/{camp['id']}", auth=mc_auth)
if report_r.status_code == 200:
detail = report_r.json()
camp["unique_opens"] = detail.get("opens", {}).get("unique_opens", 0)
camp["unique_clicks"] = detail.get("clicks", {}).get("unique_clicks", 0)
camp["bounces"] = detail.get("bounces", {}).get("hard_bounces", 0)
winning_content.append(
f"Subject: {camp['subject']}\n"
f"Preview: {camp['preview']}\n"
f"From: {camp['from_name']}\n"
f"Open: {camp['open_rate']:.0%} | Click: {camp['click_rate']:.0%}"
)
time.sleep(0.3)
samples_text = "\n\n---\n\n".join(winning_content)
voice = requests.post(f"{MB}/brand-voices", headers=MH, json={
"name": "Mailchimp: Winning Email Voice",
"description": (
"Brand voice extracted from top-performing Mailchimp campaigns. "
f"Based on {len(top)} campaigns with avg open rate "
f"{sum(c['open_rate'] for c in top)/len(top):.0%} and avg click rate "
f"{sum(c['click_rate'] for c in top)/len(top):.0%}."
),
"samples": [c["subject"] + " — " + c["preview"] for c in top],
"guidelines": (
f"Top-performing subject lines average {sum(len(c['subject']) for c in top)//len(top)} characters. "
f"Common patterns: "
+ ("personalization, " if any("{" in c["subject"] or "you" in c["subject"].lower() for c in top) else "")
+ ("urgency, " if any(w in " ".join(c["subject"].lower() for c in top) for w in ["today", "now", "last", "ending"]) else "")
+ ("questions, " if any("?" in c["subject"] for c in top) else "")
+ ("numbers/lists." if any(c["subject"][0].isdigit() for c in top) else "clarity.")
),
}).json()
print(f"Brand Voice created: {voice.get('id')}")
print(f"Based on {len(top)} top campaigns")
print(f"Avg open: {sum(c['open_rate'] for c in top)/len(top):.0%}")
print(f"Avg click: {sum(c['click_rate'] for c in top)/len(top):.0%}")
print(f"\nTop 3 subjects:")
for c in top[:3]:
print(f" {c['open_rate']:.0%} open | {c['subject']}")