有些东西让我发疯,我使用 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/