2
votes

Somthing makes me crazy, I use Sendgrid to send emails and I would like to send emails in PHP with both text/plain and text/html variants.

What I tried :

I have analyzed an email with 2 content-type. I see :

----==_mimepart_35656456787

Content-Type: text/plain; charset=UTF-8

[plain text version....]

----==_mimepart_67868876878

Content-Type: text/html; charset=UTF-8

[html version....]

Then I tried to add those 2 variants like this :

...
$from = new SendGrid\Email(null, $from);
$email = new SendGrid\Email(null, $to);
$content = new SendGrid\Content("text/plain",$body_plain);
$content1 = new SendGrid\Content("text/html",$body_html);

$mail = new SendGrid\Mail($from, $subject, $email, $content1, $content);

Result :

Here is what I get :

----==_35656456787

Content-Type: text/plain; charset=UTF-8

[plain text version....]

----==_67868876878

Content-Type: text/html; charset=UTF-8

[html version....]

The mimepart is missing.

Sendgrid also advice (here : https://sendgrid.com/docs/Classroom/Build/Format_Content/html_formatting_issues.html) to send emails using both plain and html variants. So it's probably possible...

But I tried to find how to do that and I didn't find sthg..

Question : does someone has the same problem ? how to send emails using both plain and html??

Any idea?

1

1 Answers

0
votes

I checked the source code and found the Mail() function only takes 4 arguments,

public function __construct($from, $subject, $to, $content)

so your code

$mail = new SendGrid\Mail($from, $subject, $email, $content1, $content);

shouldn't work.

You can send both HTML and Plain text without using the helper class:

// If you are using Composer (recommended)
require 'vendor/autoload.php';

// If you are not using Composer
// require("path/to/sendgrid-php/sendgrid-php.php");
$to_email="[email protected]";
$to_name="John Smith";
$subject="Testing sendgrid. See you in spam folder!";
$html="and easy to do anywhere, even with PHP<a href='https://someurl.com'>Really</a>";
$text="and easy to do anywhere, even with PHP";


$json=<<<JSON
{
  "personalizations": [
    {
      "to": [
        {
          "email": "$to_email",
          "name": "$to_name"
        }
      ],
      "subject": "$subject"
    }
  ],
  "from": {
    "email": "[email protected]",
    "name": "Your Name"
  },
  "content": [
    {
      "type": "text/plain",
      "value": "$text"
    },
    {
      "type": "text/html",
      "value": "$html"
    }
  ]
}
JSON;

$request_body = json_decode($json);

$apiKey = "yourapikey";
$sg = new \SendGrid($apiKey);

$response = $sg->client->mail()->send()->post($request_body);
echo $response->statusCode();
echo $response->body();
print_r($response->headers());