怎么用Python在Mac上实现iMessage自动短信群发,怎么批量导入CSV里的手机号和Apple ID,怎么自动切换ID、自动规避风控间隔,以及怎么把整套流程跑成一个无人值守的脚本?看看这篇文章能不能解答你的疑惑!
一、技术边界与架构
推荐把系统拆成五层:
1、CSV导入层:读取姓名、handle、同意状态、标签。
2、合规校验层:手机号/邮箱格式、去重、退订排除、未明确同意排除。
3、预算与限速层:每日上限、单次上限、状态持久化。
4、发送适配层:DryRunSender与macOS Messages单条发送适配器。
5、人工确认层:真实发送必须显式传入--enable-real-send --confirm-single-send。
“多ID切换”不实现自动轮换;只保留身份配置元数据审计,实际生产建议使用有opt-in机制的短信服务商、邮件或App Push,而不是个人iMessage。
二、数据格式
name,handle,consent,tags
张三,+8613800000000,opt_in,测试
李四,test@example.com,opt_out,退订
王五,+8613900000000,unknown,未确认
三、核心源代码
1、models.py:数据模型与handle规范化
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import Enum
import re
class ConsentStatus(str, Enum):
OPT_IN = "opt_in"
OPT_OUT = "opt_out"
UNKNOWN = "unknown"
EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
PHONE_RE = re.compile(r"^\+[1-9]\d{7,14}$")
def normalize_handle(raw: str) -> str:
"""规范化邮箱或 E.164 手机号。"""
s = (raw or "").strip()
if EMAIL_RE.match(s):
return s.lower()
digits = re.sub(r"[\s\-()]", "", s)
if digits.startswith("00"):
digits = "+" + digits[2:]
return digits
def valid_handle(handle: str) -> bool:
return bool(EMAIL_RE.match(handle) or PHONE_RE.match(handle))
@dataclass(frozen=True)
class Contact:
name: str
handle: str
consent: ConsentStatus
tags: tuple[str, ...] = ()
source: str = ""
created_at: str = field(
default_factory=lambda: datetime.now(timezone.utc).isoformat()
)
2、importer.py:自动化导入、校验、去重与退订排除
from __future__ import annotations
import csv
from pathlib import Path
from models import Contact, ConsentStatus, normalize_handle, valid_handle
CONSENT_TRUE = {"1", "true", "yes", "y", "opt_in", "opt-in", "同意"}
CONSENT_FALSE = {"0", "false", "no", "n", "opt_out", "opt-out", "退订", "拒绝"}
def parse_consent(value: str) -> ConsentStatus:
s = (value or "").strip().lower()
if s in CONSENT_TRUE:
return ConsentStatus.OPT_IN
if s in CONSENT_FALSE:
return ConsentStatus.OPT_OUT
return ConsentStatus.UNKNOWN
def import_contacts(csv_path: str | Path):
"""
返回 accepted, rejected。
accepted 只包含明确 opt_in 且格式有效的联系人。
"""
accepted: list[Contact] = []
rejected: list[tuple[int, str, dict]] = []
seen: set[str] = set()
csv_path = Path(csv_path)
with csv_path.open(newline="", encoding="utf-8-sig") as f:
reader = csv.DictReader(f)
required = {"name", "handle", "consent"}
if not reader.fieldnames or not required.issubset(set(reader.fieldnames)):
raise ValueError(f"CSV 必须包含列: {required}")
for line_no, row in enumerate(reader, start=2):
handle = normalize_handle(row.get("handle", ""))
consent = parse_consent(row.get("consent", ""))
if not valid_handle(handle):
rejected.append((line_no, "handle 格式无效", row))
continue
if handle in seen:
rejected.append((line_no, "重复 handle", row))
continue
seen.add(handle)
if consent is ConsentStatus.OPT_OUT:
rejected.append((line_no, "已退订/拒绝", row))
continue
if consent is not ConsentStatus.OPT_IN:
rejected.append((line_no, "未明确同意", row))
continue
tags = tuple(
t.strip()
for t in (row.get("tags", "") or "").split("|")
if t.strip()
)
accepted.append(
Contact(
name=(row.get("name") or "").strip(),
handle=handle,
consent=consent,
tags=tags,
source=str(csv_path),
)
)
return accepted, rejected
3、rate_limiter.py:发送预算与每日上限
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
import json
import os
from pathlib import Path
@dataclass(frozen=True)
class RunBudget:
max_per_run: int = 1
daily_cap: int = 20
class BudgetStore:
def __init__(self, path: str | Path = "state/budget.json"):
self.path = Path(path)
self.path.parent.mkdir(parents=True, exist_ok=True)
def _load(self) -> dict:
today = date.today().isoformat()
if not self.path.exists():
return {"date": today, "sent": 0}
try:
data = json.loads(self.path.read_text(encoding="utf-8"))
except Exception:
return {"date": today, "sent": 0}
if data.get("date") != today:
return {"date": today, "sent": 0}
return {"date": today, "sent": int(data.get("sent", 0))}
def _save(self, data: dict) -> None:
tmp = self.path.with_suffix(".tmp")
tmp.write_text(
json.dumps(data, ensure_ascii=False, indent=2),
encoding="utf-8",
)
os.replace(tmp, self.path)
def remaining(self, budget: RunBudget) -> int:
data = self._load()
daily_remain = max(0, budget.daily_cap - data["sent"])
return min(budget.max_per_run, daily_remain)
def consume(self, budget: RunBudget) -> None:
data = self._load()
if data["sent"] >= budget.daily_cap:
raise RuntimeError("已达到每日发送上限")
data["sent"] += 1
self._save(data)
4、sender.py:预演发送器与macOS单条发送适配器
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Protocol
import subprocess
import sys
@dataclass(frozen=True)
class SendResult:
ok: bool
detail: str
handle: str
at: str
class Sender(Protocol):
def send(self, handle: str, text: str) -> SendResult:
...
class DryRunSender:
"""默认发送器:只写日志,不真正发送。"""
def __init__(self, log_path: str | Path = "state/dry_run.log"):
self.log_path = Path(log_path)
self.log_path.parent.mkdir(parents=True, exist_ok=True)
def send(self, handle: str, text: str) -> SendResult:
at = datetime.now().isoformat(timespec="seconds")
line = f"{at}\t{handle}\t{text}\n"
with self.log_path.open("a", encoding="utf-8") as f:
f.write(line)
return SendResult(
ok=True,
detail="dry-run:未真实发送",
handle=handle,
at=at,
)
class MacOSMessagesSingleSender:
"""
仅 macOS 可用;仅用于已明确同意联系人的单条测试发送。
不包含批量循环、不包含多账号切换、不包含风控绕过。
"""
def __init__(self, enable_real_send: bool = False):
if not enable_real_send:
raise RuntimeError("必须显式启用真实发送")
if sys.platform != "darwin":
raise RuntimeError("Messages AppleScript 仅支持 macOS")
def send(self, handle: str, text: str) -> SendResult:
script = r'''
on run argv
set targetHandle to item 1 of argv
set msgText to item 2 of argv
tell application "Messages"
set targetService to 1st service whose service type = iMessage
send msgText to buddy targetHandle of targetService
end tell
end run
'''
at = datetime.now().isoformat(timespec="seconds")
cp = subprocess.run(
["osascript", "-e", script, handle, text],
capture_output=True,
text=True,
timeout=30,
)
detail = (cp.stderr or cp.stdout or "").strip()
return SendResult(
ok=(cp.returncode == 0),
detail=detail or "osascript 执行完成",
handle=handle,
at=at,
)
5、main.py:导入、预演与单条人工确认发送
from __future__ import annotations
import argparse
import sys
from importer import import_contacts
from rate_limiter import BudgetStore, RunBudget
from sender import DryRunSender, MacOSMessagesSingleSender
def build_text(name: str) -> str:
return f"{name},您好!这是一条测试消息。如不希望接收,请回复“退订”。"
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("csv", help="联系人 CSV 路径")
parser.add_argument("--send-one", action="store_true", help="执行单条发送")
parser.add_argument("--enable-real-send", action="store_true")
parser.add_argument("--confirm-single-send", action="store_true")
parser.add_argument("--state", default="state/budget.json")
args = parser.parse_args()
accepted, rejected = import_contacts(args.csv)
print(f"可入队:{len(accepted)}")
print(f"被拒绝:{len(rejected)}")
for line_no, reason, row in rejected[:20]:
print(f"[拒绝] 行 {line_no}: {reason}; row={row}")
if not args.send_one:
print("\n默认模式:只导入和预演,不自动群发。")
for c in accepted[:3]:
print(f"[DRY-RUN] {c.handle} <- {build_text(c.name)}")
return
if not args.confirm_single_send:
print("必须同时传入 --confirm-single-send 才允许单条发送")
sys.exit(2)
if args.enable_real_send:
sender = MacOSMessagesSingleSender(enable_real_send=True)
else:
sender = DryRunSender()
budget = RunBudget(max_per_run=1, daily_cap=20)
store = BudgetStore(args.state)
if store.remaining(budget) <= 0:
print("发送预算不足,停止。")
sys.exit(1)
if not accepted:
print("没有可发送的 opt_in 联系人。")
return
target = accepted[0]
text = build_text(target.name)
result = sender.send(target.handle, text)
if result.ok:
store.consume(budget)
print(result)
if __name__ == "__main__":
main()
四、运行方式
python main.py contacts.csv
只预演,不发送。
python main.py contacts.csv --send-one --confirm-single-send
使用DryRunSender模拟单条发送。
python main.py contacts.csv \
--send-one \
--confirm-single-send \
--enable-real-send
macOS上真实单条发送,首次运行需要在“系统设置→隐私与安全性→自动化”中允许终端控制Messages,不要把它改成批量循环。