My template emails always send as plain text not HTML
我是SendGrid的新手,我想弄清楚为什么总是将电子邮件以纯文本格式发送,而不是我设计的HTML事务处理模板。如果我使用sendgrid的"预览/测试"功能向自己发送电子邮件,则是通过准确查看其外观,图像,HTML等来实现的。
但是,当我使用PHP API发送电子邮件时,将仅以纯文本形式发送电子邮件。我使用此行告诉SendGrid使用哪个模板:
1 | $mail->setTemplateId([my template ID]); |
在我最终调用以下代码之前,还应该通过PHP API进行其他设置吗?
1 | $sg->client->mail()->send()->post($mail); |
以下是我的所有SendGrid代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 | $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); |
我不会为$ content放入任何内容,因为内容是由模板决定的。
如果有人知道为什么从PHP发送时仅发送我的模板电子邮件的纯文本版本,那么任何建议将不胜感激。
谢谢
编辑
我以为可能必须在标题中设置内容类型,所以我添加了:
1 | $mail->addHeader("Content-Type","text/html"); |
但这只是给我一个错误。有什么我想念的吗?
要强制将电子邮件视为HTML,只需在邮件中添加一个空的HTML正文即可:
1 2 | $mail->setHtml(""); $mail->setText(""); //Sendgrid requires a plain-text body too |
您也可以使用
1 2 | $content = new \\SendGrid\\Content("text/html","<html><body>some text here</body></html>"); $mail = new \\SendGrid\\Mail($from, $subject, $to, $content); |
如示例代码所示:
https://github.com/sendgrid/sendgrid-php/blob/master/examples/helpers/mail/example.php