2017-03-11 139 views
2

我越來越想通過SendGrid發送電子郵件時此錯誤消息:Sendgrid錯誤400錯誤請求

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", "[email protected]"); 

$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,所以我有點迷失在這個錯誤意味着什麼。

回答

2

您得到的錯誤是由於附件。

該文件的內容必須爲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

如果向下滾動到「附件」對象,展開「內容」欄,它會顯示要求它,maily:The Base64 encoded content of the attachment.