尝试通过 SendGrid 发送电子邮件时收到此错误消息:
400 { "errors": [ { "message": "Bad Request", "field": null, "help": null } ] } array(14) { [0]=> string(25) "HTTP/1.1 400 Bad Request " [1]=> string(14) "Server: nginx " [2]=> string(36) "Date: Sat, 11 Mar 2017 19:20:44 GMT " [3]=> string(31) "Content-Type: application/json " [4]=> string(19) "Content-Length: 63 " [5]=> string(23) "Connection: keep-alive " [6]=> string(22) "X-Frame-Options: DENY " [7]=> string(58) "Access-Control-Allow-Origin: https://sendgrid.api-docs.io " [8]=> string(35) "Access-Control-Allow-Methods: POST " [9]=> string(87) "Access-Control-Allow-Headers: Authorization, Content-Type, On-behalf-of, x-sg-elas-acl " [10]=> string(28) "Access-Control-Max-Age: 600 " [11]=> string(75) "X-No-CORS-Reason: https://sendgrid.com/docs/Classroom/Basics/API/cors.html " [12]=> string(1) " " [13]=> string(0) "" }
这是我的代码:
<?php
// If you are using Composer
require 'vendor/autoload.php';
use SendGrid\Mail;
$apiKey = 'mykey';
$sg = new \SendGrid($apiKey);
$email = new SendGrid\Email("Me", "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="523f333b3e12353f333b3e7c313d3f" rel="noreferrer noopener nofollow">[email protected]</a>");
$mail = new SendGrid\Mail();
$mail->setFrom($email);
$mail->setSubject("Attachment Test");
$p = new \SendGrid\Personalization();
$p->addTo($email);
$c = new \SendGrid\Content("text/plain", "Hi");
$mail->addPersonalization($p);
$mail->addContent($c);
$att1 = new \SendGrid\Attachment();
$att1->setContent( file_get_contents("favicon.ico") );
$att1->setType("text/plain");
$att1->setFilename("1.txt");
$att1->setDisposition("attachment");
$mail->addAttachment( $att1 );
$response = $sg->client->mail()->send()->post($mail);
echo $response->statusCode() . "\n";
echo json_encode( json_decode($response->body()), JSON_PRETTY_PRINT) . "\n";
var_dump($response->headers());
?>
不确定是否与附件有关。我设法使用不同的代码发送电子邮件,但我正在尝试为其添加附件,因此这是新代码。我不太了解 php,所以我有点迷失这个错误意味着什么。
最佳答案
您收到的错误是由附件引起的。
文件的内容必须采用 base64
编码。否则,由于您将随机字节引入到请求正文中,它会使 JSON 格式错误。
您可以看到,在 sendgrid-php
邮件助手的完整示例中,base64
字符串被设置为附件的内容。
https://github.com/sendgrid/sendgrid-php/blob/master/examples/helpers/mail/example.php#L83
正如您在 Attachment
类中看到的,内容只是简单地设置,并且在类序列化时将序列化为 JSON 对象中的字符串:
https://github.com/sendgrid/sendgrid-php/blob/master/lib/helpers/mail/Mail.php#L670
您只需要使用这个功能:http://php.net/manual/en/function.base64-encode.php
要更改线路:
$att1->setContent( file_get_contents("favicon.ico") );
致:
$att1->setContent( base64_encode( file_get_contents("favicon.ico") ) );
v3 邮件发送文档位于:https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/index.html
如果您向下滚动到“附件”对象并展开“内容”字段,它将显示其要求,主要:附件的 Base64 编码内容。
关于php - Sendgrid 错误 400 错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42739730/