HerrimanCoder
HerrimanCoder

Reputation: 7226

If present, text/plain and text/html may only be provided once

I keep getting this error when trying to send SendGrid emails:

If present, text/plain and text/html may only be provided once.

Here is my php code:

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();
    }
}

I'm sending these in a loop to several emails. The FIRST email sent always works fine. All 2-x emails fail with the message shown. What am I doing wrong?

Upvotes: 0

Views: 1140

Answers (1)

esqew
esqew

Reputation: 44712

Ostensibly, each time you reference the global $sendGridEmail, you're referencing and making changes to the same object. As such, when attempting to run this function more than once, you're running addContent on the message you previously already added content to.

The problem occurs because you can't have two contents of the same MIME type in a single message, which is what you're inadvertently attempting here. I would extrapolate that wherever you got this sample from was not counting on it being used in a situation where the script itself would be designed to send more than one email per execution.

There are a few ways you could work around this; the simplest is likely to just change your script slightly to un-global and reinitialize $sendGridEmail in each execution of the function.

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();
    }
}

Without seeing the rest of your script, there may be more changes required than the one I've proposed above, but it should at least get you going on the right foot.

Upvotes: 3

Related Questions