php - 发送网格 : How to use mimepart with their PHP Api

标签 php html mime-types sendgrid

有些东西让我发疯,我使用 Sendgrid 发送电子邮件,我想用 PHP 发送包含文本/纯文本和文本/html 变体的电子邮件。

我尝试了什么:

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

----==_mimepart_35656456787

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

[plain text version....]

----==_mimepart_67868876878

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

[html version....]

然后我尝试像这样添加这 2 个变体:

...
$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

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

[plain text version....]

----==_67868876878

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

[html version....]

缺少 mime 部分。

Sendgrid 还建议(此处:https://sendgrid.com/docs/Classroom/Build/Format_Content/html_formatting_issues.html)使用纯文本和 html 变体发送电子邮件。所以这可能是可能的......

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

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

有什么想法吗?

最佳答案

我查看了源代码,发现 Mail() 函数只有 4 个参数,

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

所以你的代码

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

应该行不通。

您可以在不使用辅助类的情况下发送 HTML 和纯文本:

// 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());

关于php - 发送网格 : How to use mimepart with their PHP Api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40980370/

相关文章:

jquery - 需要帮助在鼠标悬停事件的 div 上添加带箭头的标题

javascript - 如何正确加载导航栏和页面内容?

html - 为什么我不能在段落周围 float div?

wildfly - Wildfly 10 中的内容类型问题

http - mediatype、contenttype 和 mimetype 之间有什么区别?

javascript - image.onError 事件永远不会触发,但图像不是有效数据 - 需要解决方法

javascript - PHP AJAX 没有收到 SESSION

php - 无法在 Symfony 2 中使用渲染方法找到 Twig 模板

php - 如何在 laravel-dompdf 中设置景观?

用于 cloud9 IDE 的 PHP 美化器/格式化器