PHP- sendgrid将多个电子邮件添加到收件人列表返回错误500

时间:2013-10-14 08:01:04

标签: php sendgrid

我有以下代码:

static function getContext($data) {
    // use key 'http' even if you send the request to https://...
    $options = array (
        'http' => array (
            'header' => "Content-type: application/x-www-form-urlencoded\r\n",
            'method' => 'POST',
            'content' => http_build_query ( $data ) 
        ) 
    );

    return stream_context_create ( $options );
}

static function addEmailsToRecipientList($name, $emails) {

    $url = 'https://sendgrid.com/api/newsletter/lists/email/add.json';

    $temp = array();
    foreach($emails as $email){
        $temp[] = array('email' => $email, 'name' => 'unknown');
    }

    $data = array (
            'list' => $name,
            'data' => json_encode($temp),
            'api_user' => $api_user_name,
            'api_key' => $api_password
    );

    $context = SendGridAPI::getContext ( $data );
    return file_get_contents ( $url, false, $context );
}

当我向addEmailsToRecipientList传递现有列表的名称和我要添加到其中的电子邮件地址数组时,收到错误500(内部服务器错误)。

添加一封电子邮件($ temp = array('email'=> $ email,'name'=>'unknown'))工作正常。 我做错了什么?

非常感谢!

2 个答案:

答案 0 :(得分:3)

解决了! :)

//listname: the name of an existing recipients list
//$emails: an array of emails
static function addEmailsToRecipientList($listname, $emails){
    $username= 'sendgrid_username';
    $password= 'sendgrid_password';

    $url = 'https://sendgrid.com/api/newsletter/lists/email/add.json?api_user='.$username.'&api_key='.$password; 

    $str= '&list=' . $listname;  
    for ($i=0;$i<count($emails);$i++) {
        $str.= '&data[]={"email":"'.$emails[$i] . '","name":"unknown'. $i .'"}';
    }

    return file_get_contents($url . $str);
}

答案 1 :(得分:0)

带有一些触摸的脚本工作得很好,我添加了电子邮件的urlencode,json_decode和模拟名称。

    $url = 'https://sendgrid.com/api/newsletter/lists/email/add.json?api_user='.$username.'&api_key='.$password; 

    $str= '&list=' . $listname;  
    foreach ($data as $email) {
        $attributes = explode("@", $email);
        $str.= '&data[]=';
        $str.= urlencode('{"email":"'. $email . '","name":"'. ucfirst($attributes[0]) .'"}');
    }

    $results = file_get_contents($url . $str);
    $results = json_decode($results, TRUE);
    return (isset($results['inserted'])) ? $results['inserted'] : 0;