YOKA
YOKA

Reputation: 43

PHP- sendgrid add multiple emails to a recipient list returns error 500

I have the following code:

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 );
}

When I pass to addEmailsToRecipientList a name of an existing list and an array of email addresses that I want to add to it, I get an error 500 (internal server error).

Adding a single email ($temp = array('email' => $email, 'name' => 'unknown')) works fine. What am I doing wrong?

Thanks a lot!

Upvotes: 0

Views: 1201

Answers (2)

Herduin
Herduin

Reputation: 19

The scripts with a some touchs works very fine, i add the urlencode, the json_decode and simulated name for the email.

    $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;

Upvotes: 0

YOKA
YOKA

Reputation: 43

Solved it! :)

//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);
}

Upvotes: 3

Related Questions