0

I'm new to SendGrid and I'm trying to work out why the emails are always sent as plain text instead of the designed HTML transactional template I've made. If I use the sendgrid "preview/test" feature to send myself the email, it comes through looking exactly how it should, images, HTML etc.

However, when I use the PHP API to send the email, the email is sent but only in plain text. I use this line to tell SendGrid which template to use:

$mail->setTemplateId([my template ID]);

Are there some other things I should be setting via the PHP API before I finally call the following?

$sg->client->mail()->send()->post($mail);

Below is all my SendGrid code:

$from = new SendGrid\Email([website name], [website email address]);
$subject = "test subject";
$to = new SendGrid\Email(null, $email);
$content = "";
$mail = new SendGrid\Mail($from, $subject, $to, $content);
$mail->setTemplateId([my template ID]);
//$mail->setASMGroupId(3057);
$mail->personalization[0]->addSubstitution("%email%", $email);
$mail->personalization[0]->addSubstitution("%hash%", $hash);
$apiKey = [my api key];
$sg = new \SendGrid($apiKey);

$response = $sg->client->mail()->send()->post($mail);

I dont put anything in for the $content because the content is dictated in the template.

If anyone has any idea why it's only sending a plain text version of my templated email when sent from PHP, any advice would be much appreciated.

Thank you

EDIT

I thought I might have to set the content-type in the header so I added:

$mail->addHeader("Content-Type", "text/html");

But this just gives me an error. Is there something I'm missing?

poncho
  • 1,100
  • 2
  • 15
  • 38

2 Answers2

2

To force the email to be treated as HTML, just add an empty HTML body to the message:

$mail->setHtml(" ");
$mail->setText(""); //Sendgrid requires a plain-text body too
-1

You can also use

$content = new \SendGrid\Content("text/html", "<html><body>some text here</body></html>");
$mail = new \SendGrid\Mail($from, $subject, $to, $content);

as shown in the example code: https://github.com/sendgrid/sendgrid-php/blob/master/examples/helpers/mail/example.php

Ersin Demirtas
  • 666
  • 6
  • 14
  • That has nothing to do with why my emails were sending as plain text rather than HTML. Thank you for the response but I think you have misunderstood the question. – poncho Jan 19 '18 at 13:14