
在 SendGrid 中批量发送多封邮件时,若需为不同收件人指定不同的 content-type(如部分用 text/plain、部分用 text/html),必须为每封邮件创建独立的 Mail 实例,否则会因重复添加内容类型触发“text/plain and text/html may only be provided once”错误。
在 sendgrid 中批量发送多封邮件时,若需为不同收件人指定不同的 content-type(如部分用 text/plain、部分用 text/html),必须为每封邮件创建独立的 `mail` 实例,否则会因重复添加内容类型触发“text/plain and text/html may only be provided once”错误。
SendGrid 的 Mail 对象设计为单封邮件的完整封装单元,其 addContent() 方法是追加式操作(而非覆盖),因此反复调用会导致同一邮件中出现多个 text/plain 或 text/html 内容块——这违反了 MIME 规范,服务端将拒绝该请求,并返回明确错误:
{"message":"If present, text/plain and text/html may only be provided once.","field":"content"}
根本原因在于:你复用了同一个 $mail 实例(如在循环外初始化),并在每次迭代中不断调用 addContent() 和 addPersonalization()。结果是,第二封邮件不仅携带自己的收件人和内容,还“继承”了第一封邮件的全部内容字段,造成冲突。
✅ 正确做法是:在 foreach 循环内部新建 Mail 实例,并完成构建与发送全流程。示例如下:
use SendGrid\Mail\Mail;
foreach ($emailAddress as $key => $email) {
// ✅ 每次循环创建全新 Mail 实例
$mail = new Mail();
// 设置发件人(全局统一)
$mail->setFrom(new From("sender@example.com", "Your App"));
// 添加个性化收件人
$personalization = new Personalization();
$personalization->addTo(new To(trim($email)));
$mail->addPersonalization($personalization);
// ✅ 根据邮箱地址动态选择 content-type
if (in_array(trim($email), ["test1@example.com", "admin@example.com"])) {
$mail->addContent(
"text/plain",
str_replace(" ", "", $messagePlain)
);
$mail->setSubject($subject . " [Plain]");
} else {
$mail->addContent(
"text/html",
nl2br($message)
);
$mail->setSubject($subject . " [HTML]");
}
// ✅ 立即发送当前邮件(使用独立实例)
$sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
try {
$response = $sendgrid->send($mail);
echo "Email to {$email} sent: {$response->statusCode()}";
} catch (Exception $e) {
error_log("SendGrid error for {$email}: " . $e->getMessage());
}
}
⚠️ 关键注意事项:
-
不要在循环外声明
$mail:确保每次迭代都new Mail(); -
setFrom()、setSubject()等通用字段可在此处设置,但避免跨邮件复用内容对象; - 若需统一模板逻辑,建议封装为工厂函数(如
buildMailForRecipient($email, $messagePlain, $message)); - 生产环境务必添加异常捕获与日志记录,避免单封失败阻断整个队列;
- 高频发送请结合 SendGrid 的批量发送 API(
/v3/mail/send批量模式)或队列异步处理,而非同步逐封调用。
遵循此模式,即可安全、灵活地为不同收件人交付适配其终端能力的内容格式(如纯文本终端用户 vs 富文本邮箱客户端),同时严格符合 SendGrid 的 API 约束与电子邮件标准规范。










