Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewrite Mailgun curl script for PHP

Tags:

php

curl

mailgun

The mailgun API documentation suggest using the following script for adding users to a mailing list via curl:

curl -s --user 'api:YOUR_API_KEY' \
https://api.mailgun.net/v3/lists/LIST@YOUR_DOMAIN_NAME/members \
-F subscribed=True \
-F address='[email protected]' \
-F name='Bob Bar' \
-F description='Developer' \
-F vars='{"age": 26}'

I am trying to rewrite this so that it works with PHP:

$data = json_encode(array(
  "subscribed"  => "True",
  "address" => "[email protected]",
  "name" => "Bob Bar"
));

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://api.mailgun.net/v3/lists/LIST@YOUR_DOMAIN_NAME/members');
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "api:{YOUR_API_KEY}");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_POST, true); 
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

$result = curl_exec($curl);
curl_close($curl);
print_r($result);

I am obviously replacing both https://api.mailgun.net/v3/lists/LIST@YOUR_DOMAIN_NAME/members and YOUR_API_KEY with the appropriate strings, however it is failing. Can anyone see where I am going wrong?

Many thanks.

like image 591
user2743326 Avatar asked Dec 07 '25 16:12

user2743326


1 Answers

Resolved using the following code:

$data = array(
  "subscribed"  => "True",
  "address" => "[email protected]",
  "name" => "Bob Bar"
);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://api.mailgun.net/v3/lists/LIST@YOUR_DOMAIN_NAME/members');
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "api:YOUR_API_KEY");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_POST, true); 
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

$result = curl_exec($curl);
curl_close($curl);
print_r($result);

Hope this helps someone.

like image 114
user2743326 Avatar answered Dec 11 '25 07:12

user2743326



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!