2016-12-05 20 views
2

Somthing讓我發瘋,我使用Sendgrid發送電子郵件,並且我想用text/plain和text/html兩種變體以PHP發送電子郵件。Sendgrid:如何使用mimepart與他們的PHP Api

我試了一下:

我分析有2內容類型的電子郵件。我看到:

---- == _ mimepart_35656456787

的Content-Type:text/plain的;字符集= UTF-8

[純文本版本....]

---- == _ mimepart_67868876878

的Content-Type:text/html的;字符集= 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

Content-Type:text/plain;字符集= UTF-8

[純文本版本....]

---- == _ 67868876878

的Content-Type:text/html的;字符集= UTF-8

[HTML版本....]

的mimepart缺失。

Sendgrid還建議(這裏:https://sendgrid.com/docs/Classroom/Build/Format_Content/html_formatting_issues.html)使用普通和html變體發送電子郵件。因此它可能是可能的...

但我試圖找到如何做到這一點,我沒有找到STHG ..

問:是否有人有同樣的問題?如何使用普通和html發送電子郵件?

有什麼想法?

回答

0

我檢查了源代碼,發現該郵件()函數只需要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="[email protected]"; 
$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": "[email protected]", 
    "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());