0

我有以下代码:

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')) 工作正常。我究竟做错了什么?

非常感谢!

4

2 回答 2

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);
}
于 2013-10-17T06:39:04.033 回答
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;
于 2014-08-03T00:39:30.593 回答