【问题标题】:Sendgrid : How to use mimepart with their PHP ApiSendgrid:如何在他们的 PHP Api 中使用 mimepart
【发布时间】:2017-04-20 04:58:15
【问题描述】:

某事让我发疯,我使用 Sendgrid 发送电子邮件,我想用 PHP 发送带有 text/plain 和 text/html 变体的电子邮件。

我尝试了什么:

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

----==_mimepart_35656456787

内容类型:文本/纯文本; charset=UTF-8

[纯文本版本....]

----==_mimepart_67868876878

内容类型:文本/html; charset=UTF-8

[html 版本....]

然后我尝试像这样添加这 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

内容类型:文本/纯文本; charset=UTF-8

[纯文本版本....]

----==_67868876878

内容类型:文本/html; charset=UTF-8

[html 版本....]

mimepart 不见了。

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

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

问题:有人有同样的问题吗?如何同时使用纯文本和 html 发送电子邮件??

有什么想法吗?

【问题讨论】:

    标签: php html mime-types sendgrid


    【解决方案1】:

    查了源码发现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());
    

    【讨论】:

      猜你喜欢
      • 2011-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2015-07-20
      • 1970-01-01
      相关资源
      最近更新 更多