Home > Software design >  Sendgrid multiple emails with different contentType?
Sendgrid multiple emails with different contentType?

Time:09-22

Im trying to send multiple emails with Sendgrid, and everything works fine, unless i change Content type meanwhile.

Is it possible to change contentType determined which email im sending to?

The error:

{"message":"If present, text/plain and text/html may only be provided once.","field":"content","help":null}]

Code:

    foreach ($emailAddress as $key => $email) {
        $addresses["$email"] = "$key";
        $perzon = new Personalization();
        $perzon->addTo(new To((trim($email))));
        $mail->addPersonalization($perzon);

        if ($email == "[email protected]" || $email == "[email protected]") {
            $mail->addContent(
                "text/plain",
                str_replace("   ", "", $messagePlain)
            );
            $mail->setSubject($subject);
        } else {
            $mail->addContent(
                "text/html",
                nl2br($message)
            );
            $mail->setSubject($subject);
        }
    }

CodePudding user response:

It looks like you're re-using the $mail object each time you loop. And addContent() adds extra content to the email (clue's in the name! :-)), it doesn't overwrite existing content. So by the time you're on the second email you could have added two lots of plaintext content (for example), and the mailing class can't cope with that because it doesn't know which version of the plaintext content you really want to send - an email cannot contain more than one version of the same kind of content (because if it did, again the receiving client wouldn't know which version to display either).

So wherever you are declaring the $mail object (it isn't shown in your question), you need to move that line inside your foreach loop and that should resolve the issue, because you'll have a fresh instance of the email object each time, instead of keep adding things to an existing one.

Also I'd expect you need to move the code which sends the email inside the loop too, otherwise it'll only send once (using whatever was the last settings generated by the loop).

  • Related