Sendgrid:如何在PHP Api中使用mimepart

Sendgrid:如何在PHP Api中使用mimepart,php,html,mime-types,sendgrid,Php,Html,Mime Types,Sendgrid,有些事情让我抓狂,我使用Sendgrid发送电子邮件,我想用PHP发送包含text/plain和text/html变体的电子邮件 我的尝试: 我分析了一封内容类型为2的电子邮件。我明白了: ----==\u mimepart\u 35656456787 内容类型:文本/纯文本;字符集=UTF-8 [纯文本版本….] ----==\u mimepart\u 67868876878 内容类型:text/html;字符集=UTF-8 [html版本….] 然后我尝试添加以下两种变体: ... $fro

有些事情让我抓狂,我使用Sendgrid发送电子邮件,我想用PHP发送包含text/plain和text/html变体的电子邮件

我的尝试:

我分析了一封内容类型为2的电子邮件。我明白了:

----==\u mimepart\u 35656456787

内容类型:文本/纯文本;字符集=UTF-8

[纯文本版本….]

----==\u mimepart\u 67868876878

内容类型:text/html;字符集=UTF-8

[html版本….]

然后我尝试添加以下两种变体:

...
$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);
结果:

以下是我得到的:

----==_35656456787

内容类型:文本/纯文本;字符集=UTF-8

[纯文本版本….]

----==_67868876878

内容类型:text/html;字符集=UTF-8

[html版本….]

mimepart不见了

Sendgrid还建议(此处:)使用普通和html变体发送电子邮件。所以很可能

但我试图找到如何做到这一点,但我没有找到sthg

问题:有人也有同样的问题吗?如何使用普通和html发送电子邮件


有什么想法吗?

我检查了源代码,发现Mail()函数只接受4个参数

public function __construct($from, $subject, $to, $content)
所以你的代码

$mail = new SendGrid\Mail($from, $subject, $email, $content1, $content);
不应该工作

您可以发送HTML和纯文本,而无需使用helper类:

// 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="recepient@somedomain.com";
$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": "youremail@somedomain.com",
    "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());
//如果您使用的是Composer(推荐)
需要“vendor/autoload.php”;
//如果您没有使用Composer
//require(“path/to/sendgrid php/sendgrid php.php”);
$to_电子邮件=”recepient@somedomain.com";
$to_name=“John Smith”;
$subject=“正在测试sendgrid。垃圾邮件文件夹中见!”;
$html=“而且在任何地方都可以轻松操作,即使使用PHP”;
$text=“而且在任何地方都可以轻松操作,即使使用PHP”;
$json=send()->post($request\u body);
echo$response->statusCode();
echo$response->body();
打印($response->headers());