suppress-global-unsubscribes
정보
이 스킬은 법적 준수를 보장하고 비용 절감을 위해 HubSpot에서 전역적으로 구독 취소된 연락처를 식별합니다. API를 통해 연락처를 탐지 및 감사하고, 마케팅 상태 필드가 읽기 전용이므로 UI를 통해 수동으로 차단을 처리하는 하이브리드 방식을 사용합니다. 법적으로 이메일을 보낼 수 없는 연락처를 찾아 관리하여 데이터베이스 정리 작업에 활용하세요.
빠른 설치
Claude Code
추천npx skills add TomGranot/hubspot-admin-skills -a claude-code/plugin add https://github.com/TomGranot/hubspot-admin-skillsgit clone https://github.com/TomGranot/hubspot-admin-skills.git ~/.claude/skills/suppress-global-unsubscribesClaude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요
문서
Suppress Globally Unsubscribed Contacts
Purpose
Contacts who have globally unsubscribed cannot legally be sent marketing emails under CAN-SPAM, GDPR, or CASL. Despite this, they may still be classified as "marketing contacts" in HubSpot, meaning the organization is paying for contacts it cannot and must not email. This skill identifies all globally unsubscribed contacts, analyzes their lifecycle distribution, and guides suppression.
Prerequisites
- A HubSpot private app access token with
crm.objects.contacts.readandcrm.lists.read/crm.lists.writescopes - Python 3.10+ with
uvfor package management - A
.envfile containingHUBSPOT_ACCESS_TOKEN - Super Admin or Marketing Hub Admin permissions for the manual UI suppression step
Key Constraint
hs_marketable_status is read-only via the API. The API handles discovery and audit. Actual suppression must happen in the HubSpot UI.
Execution Pattern
This skill follows a 4-stage execution pattern: Plan -> Before State -> Execute -> After State.
Stage 1: Plan
Before writing any code, confirm with the user:
- Do not re-subscribe anyone. Even if the unsubscribe pattern looks like a batch import error, re-subscribing contacts without explicit consent violates CAN-SPAM and GDPR.
- Billing impact: Non-marketing status changes take effect at the start of the next billing cycle.
- Investigate uniform patterns: If all subscription types show nearly identical unsubscribe counts, this suggests a batch event (migration, import error, compliance sweep) rather than organic opt-outs. Understanding the origin prevents recurrence.
Stage 2: Before State
Count globally unsubscribed contacts, break down by lifecycle stage, and generate an audit CSV.
"""
Before State: Count globally unsubscribed contacts.
Note: >10K results means the Search API pagination limit may apply.
Uses count-only queries and segmented exports.
"""
import os
import csv
import time
import requests
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.environ["HUBSPOT_ACCESS_TOKEN"]
BASE = "https://api.hubapi.com"
headers = {
"Authorization": f"Bearer {TOKEN}",
"Content-Type": "application/json",
}
url = f"{BASE}/crm/v3/objects/contacts/search"
# --- Step 1: Total count ---
resp = requests.post(url, headers=headers, json={
"filterGroups": [{"filters": [
{"propertyName": "hs_email_optout", "operator": "EQ", "value": "true"}
]}],
"limit": 1,
})
resp.raise_for_status()
total_unsubscribed = resp.json().get("total", 0)
print(f"Total globally unsubscribed: {total_unsubscribed}")
# --- Step 2: How many are still marketing? ---
resp2 = requests.post(url, headers=headers, json={
"filterGroups": [{"filters": [
{"propertyName": "hs_email_optout", "operator": "EQ", "value": "true"},
{"propertyName": "hs_marketable_status", "operator": "EQ", "value": "true"},
]}],
"limit": 1,
})
resp2.raise_for_status()
still_marketing = resp2.json().get("total", 0)
already_non_marketing = total_unsubscribed - still_marketing
print(f"Still marketing (need suppression): {still_marketing}")
print(f"Already non-marketing: {already_non_marketing}")
# --- Step 3: Lifecycle stage breakdown ---
print("\nLifecycle stage breakdown:")
stages = [
"lead", "subscriber", "marketingqualifiedlead",
"salesqualifiedlead", "opportunity", "customer",
"evangelist", "other",
]
for stage in stages:
resp_s = requests.post(url, headers=headers, json={
"filterGroups": [{"filters": [
{"propertyName": "hs_email_optout", "operator": "EQ", "value": "true"},
{"propertyName": "lifecyclestage", "operator": "EQ", "value": stage},
]}],
"limit": 1,
})
if resp_s.status_code == 200:
count = resp_s.json().get("total", 0)
if count > 0:
print(f" {stage}: {count}")
time.sleep(0.1)
# Check contacts with no lifecycle stage
resp_empty = requests.post(url, headers=headers, json={
"filterGroups": [{"filters": [
{"propertyName": "hs_email_optout", "operator": "EQ", "value": "true"},
{"propertyName": "lifecyclestage", "operator": "NOT_HAS_PROPERTY"},
]}],
"limit": 1,
})
if resp_empty.status_code == 200:
empty_count = resp_empty.json().get("total", 0)
if empty_count > 0:
print(f" (no lifecycle stage): {empty_count}")
CRITICAL: API pagination limit. The HubSpot CRM Search API caps at 10,000 results per query. For larger sets, use segmented queries to get complete exports.
# --- Step 4: Export CSV using segmented queries ---
# If total > 10K, segment by lifecycle stage to bypass the pagination cap.
PROPS = [
"email", "firstname", "lastname", "hs_email_optout",
"hs_marketable_status", "lifecyclestage", "createdate",
]
all_contacts = []
if total_unsubscribed <= 10000:
# Simple pagination
segments = [(None, None)] # No lifecycle filter needed
else:
# Segment by lifecycle stage to keep each under 10K
segments = [
("lifecyclestage", "lead"),
("lifecyclestage", "subscriber"),
("lifecyclestage", "marketingqualifiedlead"),
("lifecyclestage", "salesqualifiedlead"),
("lifecyclestage", "opportunity"),
("lifecyclestage", "customer"),
("lifecyclestage", "evangelist"),
("lifecyclestage", "other"),
("lifecyclestage", None), # NOT_HAS_PROPERTY
]
for seg_prop, seg_value in segments:
after = None
seg_filters = [
{"propertyName": "hs_email_optout", "operator": "EQ", "value": "true"},
]
if seg_prop and seg_value:
seg_filters.append(
{"propertyName": seg_prop, "operator": "EQ", "value": seg_value}
)
elif seg_prop and seg_value is None:
seg_filters.append(
{"propertyName": seg_prop, "operator": "NOT_HAS_PROPERTY"}
)
while True:
payload = {
"filterGroups": [{"filters": seg_filters}],
"properties": PROPS,
"limit": 100,
}
if after:
payload["after"] = after
resp = requests.post(url, headers=headers, json=payload)
if resp.status_code != 200:
break
data = resp.json()
for contact in data.get("results", []):
props = contact.get("properties", {})
all_contacts.append({
"id": contact["id"],
"email": props.get("email", ""),
"firstname": props.get("firstname", ""),
"lastname": props.get("lastname", ""),
"unsubscribed": props.get("hs_email_optout", ""),
"marketable_status": props.get("hs_marketable_status", ""),
"lifecycle_stage": props.get("lifecyclestage", ""),
"createdate": props.get("createdate", ""),
})
paging = data.get("paging", {})
after = paging.get("next", {}).get("after")
if not after:
break
time.sleep(0.15)
# Save CSV
os.makedirs("data/audit-logs", exist_ok=True)
csv_path = "data/audit-logs/globally-unsubscribed-contacts.csv"
with open(csv_path, "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=[
"id", "email", "firstname", "lastname",
"unsubscribed", "marketable_status", "lifecycle_stage", "createdate",
])
writer.writeheader()
writer.writerows(all_contacts)
print(f"\nAudit CSV saved: {csv_path} ({len(all_contacts)} records)")
if len(all_contacts) < total_unsubscribed:
print(f"Warning: {total_unsubscribed - len(all_contacts)} contacts "
f"not captured (pagination limits)")
Present findings to the user before proceeding. Key data points:
- Total unsubscribed contacts
- How many are still billed as marketing (this is the actionable number)
- Lifecycle breakdown (are any customers unsubscribed? That warrants investigation)
Stage 3: Execute
Step 3a: Create a HubSpot active list via API
"""
Execute (API part): Create a HubSpot active list for unsubscribed contacts.
"""
list_payload = {
"name": "CLEANUP: Globally Unsubscribed",
"objectTypeId": "0-1",
"processingType": "DYNAMIC",
"filterBranch": {
"filterBranchType": "OR",
"filterBranches": [
{
"filterBranchType": "AND",
"filterBranches": [],
"filters": [
{
"filterType": "PROPERTY",
"property": "hs_email_optout",
"operation": {
"operationType": "ENUMERATION",
"operator": "IS_EQUAL_TO",
"value": "true",
},
}
],
}
],
"filters": [],
},
}
resp = requests.post(
f"{BASE}/crm/v3/lists", headers=headers, json=list_payload,
)
if resp.status_code in (200, 201):
list_data = resp.json()
list_id = list_data.get("listId") or list_data.get("list", {}).get("listId")
print(f"List created! ID: {list_id}")
elif resp.status_code == 409:
print("List already exists (409 conflict). Use the existing list.")
else:
print(f"Failed: {resp.status_code} — {resp.text[:300]}")
Step 3b: Suppress contacts in HubSpot UI
Instruct the user to perform these steps manually:
- Open the list "CLEANUP: Globally Unsubscribed" in HubSpot
- Click the checkbox in the table header row
- Click "Select all N contacts in this list" in the blue banner
- Click More > Set marketing contact status
- Select Set as non-marketing contact
- Click Confirm
- For large lists (10K+), HubSpot may process this in batches over several minutes
Step 3c: Keep the list active permanently
Do NOT delete this list. It is DYNAMIC and will automatically capture future unsubscribes. Recommend running this suppression process monthly or setting up a HubSpot workflow:
- Trigger:
Unsubscribed from all emailis equal toTrue - Action: Set marketing contact status to non-marketing
Stage 4: After State
Re-run the Before State marketing status query. The still_marketing count should be zero.
"""
After State: Verify unsubscribed contacts are suppressed.
"""
resp = requests.post(url, headers=headers, json={
"filterGroups": [{"filters": [
{"propertyName": "hs_email_optout", "operator": "EQ", "value": "true"},
{"propertyName": "hs_marketable_status", "operator": "EQ", "value": "true"},
]}],
"limit": 1,
})
resp.raise_for_status()
remaining = resp.json().get("total", 0)
if remaining == 0:
print("SUCCESS: All globally unsubscribed contacts are non-marketing.")
else:
print(f"WARNING: {remaining} unsubscribed contacts are still marketing.")
Safety Mechanisms
| Mechanism | Detail |
|---|---|
| CSV audit trail | Full export of all unsubscribed contacts before any action. |
| Lifecycle breakdown | Surfaces unsubscribed customers for investigation before suppression. |
| Non-destructive | Contacts are set to non-marketing, not deleted. CRM data is preserved. |
| Active list | DYNAMIC list captures future unsubscribes automatically. |
| Confirmation prompt | Always present findings and wait for explicit user confirmation. |
Technical Gotchas
-
API pagination limit is 10K contacts. The HubSpot CRM Search API cannot return more than 10,000 results per query, even with pagination. For datasets larger than 10K, use segmented queries -- add a secondary filter (lifecycle stage, create date range, etc.) to break the set into chunks under 10K each.
-
hs_email_optoutis the correct property. The filter ishs_email_optout EQ true. Do not confuse with subscription-type-specific opt-outs (e.g.,hs_email_optout_<ID>), which are per-subscription. -
List API filter syntax differs from Search API. The Lists API uses
operationType: "ENUMERATION"withoperator: "IS_EQUAL_TO", while the Search API usesoperator: "EQ". These are different APIs with different schemas. -
Uniform unsubscribe patterns are suspicious. If all subscription types show nearly identical counts, it indicates a batch event (import, migration, compliance sweep) rather than organic opt-outs. Flag this for the user.
-
Do not re-subscribe contacts. Even if a batch unsubscribe was an error, the only legally compliant path is to contact them through a non-email channel and ask them to re-subscribe via an opt-in form.
-
hs_marketable_statusis read-only via API. Same constraint as suppress-hard-bounced. See that skill's gotchas for the custom-property-flag workaround.
Package Setup
uv init hubspot-cleanup
cd hubspot-cleanup
uv add requests python-dotenv
Create a .env file:
HUBSPOT_ACCESS_TOKEN=pat-na1-xxxxxxxx
GitHub 저장소
연관 스킬
executing-plans
디자인executing-plans 스킬은 검토 체크포인트가 포함된 통제된 배치로 실행할 완전한 구현 계획이 있을 때 사용합니다. 이 스킬은 계획을 불러와 비판적으로 검토한 후, 소규모 배치(기본값 3개 작업)로 작업을 실행하면서 각 배치 사이에 진행 상황을 아키텍트 검토를 위해 보고합니다. 이를 통해 내재된 품질 관리 체크포인트를 갖춘 체계적인 구현이 보장됩니다.
requesting-code-review
디자인이 스킬은 코드 변경 사항을 요구 사항에 따라 분석하기 위해 코드 리뷰어 하위 에이전트를 호출합니다. 작업 완료 후, 주요 기능 구현 후, 또는 메인 브랜치에 병합하기 전에 사용해야 합니다. 이 리뷰는 현재 구현체와 원래 계획을 비교하여 문제를 조기에 발견하는 데 도움이 됩니다.
connect-mcp-server
디자인이 스킬은 개발자들이 HTTP, stdio 또는 SSE 전송 방식을 통해 MCP 서버를 Claude Code에 연결하는 포괄적인 가이드를 제공합니다. GitHub, Notion 및 사용자 정의 API와 같은 외부 서비스를 통합하기 위한 설치, 구성, 인증 및 보안을 다룹니다. MCP 통합 설정, 외부 도구 구성 또는 Claude의 모델 컨텍스트 프로토콜 작업 시 활용하세요.
web-cli-teleport
디자인이 스킬은 작업 분석을 기반으로 개발자가 Claude Code 웹 인터페이스와 CLI 인터페이스 중 선택할 수 있도록 돕고, 두 환경 간 원활한 세션 텔레포트를 가능하게 합니다. 웹, CLI 또는 모바일 환경 전환 시 세션 상태와 컨텍스트를 관리하여 워크플로를 최적화합니다. 다양한 단계에서 서로 다른 도구가 필요한 복잡한 프로젝트에 사용하세요.
