2017-04-25 159 views
2

我有简单的sendgrid php脚本来发送电子邮件,这里只有问题是我需要添加更多的收件人,所以这段代码只适用于一个收件人,我正在查看官方文档,但无法找到任何有用的信息,有没有人知道如何以及我需要在这里更改以添加更多收件人/电子邮件。Sendgrid php发送给多个收件人

function sendEmail($subject, $to, $message) { 
    $from = new SendGrid\Email(null, "[email protected]"); 
    $subject = $subject; 

    $to = new SendGrid\Email(null, $to); 
    $content = new SendGrid\Content("text/html", $message); 
    $mail = new SendGrid\Mail($from, $subject, $to, $content); 

    $apiKey = 'MY_KEY'; 
    $sg = new \SendGrid($apiKey); 

    $response = $sg->client->mail()->send()->post($mail); 
    echo $response->statusCode(); 
} 
+1

呼吁每个电子邮件地址的功能。 – muttonUp

+0

代码示例请? –

+1

真的吗?循环访问您的地址并调用该函数。 – muttonUp

回答

3

SendGrid\Mail类支持通过SendGrid\Personalization类添加多个to地址。

这里你可以看到一个例子:https://github.com/sendgrid/sendgrid-php/blob/master/examples/helpers/mail/example.php#L31-L35

一个Personalization的信封电子邮件的思考。它包含收件人的地址和其他类似数据。每个Sendgrid\Mail对象,必须至少有一个Personalization

通过您所使用的构造方法,你已经创建了一个Personalization对象,在这里看到:https://github.com/sendgrid/sendgrid-php/blob/master/lib/helpers/mail/Mail.php#L951-L958

您可以创建一个Mail对象without this后来add your ownPersonalization

+0

谢谢你帮助我做到这一点,我粘贴了下面的最终代码。 –

+1

@ SuperMario'sYoshi你应该接受这个答案,如果它帮助你。 – ceejayoz

2

最后,这是我如何设法做到这一点,它的运作良好。

function sendEmail($subject, $to, $message, $cc) { 
$from = new SendGrid\Email(null, "[email protected]"); 
$subject = $subject; 

$to = new SendGrid\Email(null, $to); 
$content = new SendGrid\Content("text/html", $message); 
$mail = new SendGrid\Mail($from, $subject, $to, $content); 

foreach ($cc as $value) { 
    $to = new SendGrid\Email(null, $value); 
    $mail->personalization[0]->addCC($to); 
} 

$apiKey = 'MY_KEY'; 
$sg = new \SendGrid($apiKey); 

$response = $sg->client->mail()->send()->post($mail); 
echo $response->statusCode(); 

}

1
function makeEmail($to_emails = array(),$from_email,$subject,$body) { 
    $from = new SendGrid\Email(null, $from_email); 

    $to = new SendGrid\Email(null, $to_emails[0]); 
    $content = new SendGrid\Content("text/plain", $body); 
    $mail = new SendGrid\Mail($from, $subject, $to, $content); 
    $to = new SendGrid\Email(null, $to_emails[1]); 
    $mail->personalization[0]->addTo($to); 

    return $mail; 
} 

function sendMail($to = array(),$from,$subject,$body) { 

    $apiKey = 'your api key'; 
    $sg = new \SendGrid($apiKey); 
    $request_body = makeEmail($to ,$from,$subject,$body); 
    $response = $sg->client->mail()->send()->post($request_body); 
    echo $response->statusCode(); 
    echo $response->body(); 
    print_r($response->headers()); 
} 

$to = array('[email protected]','[email protected]'); 
$from = '[email protected]'; 
$subject = "Test Email Subject"; 
$body = "Send Multiple Person"; 

sendMail($to ,$from,$subject,$body); 
相关问题