如果存在,则只能提供一次text / plain和text / html

问题描述

在尝试发送SendGrid电子邮件时,我不断收到此错误消息:

如果存在,则只能提供一次text / plain和text / html。

这是我的PHP代码

function SendGridEmail($emailTo,$subject,$body){
    global $sendGridEmail,$mailSender,$mailSenderdisplay,$sendGridAPIKey;
    
    $sendGridEmail->setFrom($mailSender,$mailSenderdisplay);
    $sendGridEmail->setSubject($subject);
    $sendGridEmail->addTo($emailTo,$emailTo);
    $sendGridEmail->addContent("text/html",$body);
    
    $sendgrid = new \SendGrid($sendGridAPIKey);
    
    try {
        $response = $sendgrid->send($sendGridEmail);
        return $response;
    } catch (Exception $e) {
        return 'SendGrid error: '. $e->getMessage();
    }
}

我正在将它们循环发送到几封电子邮件中。发送的第一封电子邮件始终可以正常运行。所有2-x电子邮件均失败,并显示消息。我在做什么错了?

解决方法

表面上,每次您引用global $sendGridEmail时,您都是在引用并更改同一对象。因此,当尝试多次运行此功能时,您正在对先前已向其添加内容的消息运行addContent

出现此问题是因为您不能在一条消息中包含两个具有相同MIME类型的内容,而这正是您在无意中尝试的。我可以推断出,无论您从何处获得此样本,都不会指望在脚本本身被设计为每次执行发送多封电子邮件的情况下使用它。

有几种方法可以解决此问题;最简单的方法可能是在每次执行函数时将脚本稍微更改为取消global并重新初始化$sendGridEmail

function SendGridEmail($emailTo,$subject,$body){
    global $mailSender,$mailSenderDisplay,$sendGridAPIKey;
    $sendGridEmail = new \SendGrid\Mail\Mail();
    
    $sendGridEmail->setFrom($mailSender,$mailSenderDisplay);
    $sendGridEmail->setSubject($subject);
    $sendGridEmail->addTo($emailTo,$emailTo);
    $sendGridEmail->addContent("text/html",$body);
    
    $sendgrid = new \SendGrid($sendGridAPIKey);
    
    try {
        $response = $sendgrid->send($sendGridEmail);
        return $response;
    } catch (Exception $e) {
        return 'SendGrid error: '. $e->getMessage();
    }
}

没有看到脚本的其余部分,可能需要的更改比我上面提出的要多,但这至少应该使您步入正轨。