mailgun send email to multiple users - php

i have the following mailgun.php file:
define('MAILGUN_URL', 'https://api.eu.mailgun.net/v3/my_domain');
define('MAILGUN_KEY', 'xxxxxxxxx');
function sendmailbymailgun($to,$toname,$mailfromnane,$mailfrom,$subject,$html,$text,$tag,$replyto){
$array_data = array(
'from'=> $mailfromnane .'<'.$mailfrom.'>',
'to'=>$toname.'<'.$to.'>',
'subject'=>$subject,
'html'=>$html,
'text'=>$text,
'o:tracking'=>'yes',
'o:tracking-clicks'=>'yes',
'o:tracking-opens'=>'yes',
'o:tag'=>$tag,
'h:Reply-To'=>$replyto
);
$session = curl_init(MAILGUN_URL.'/messages');
curl_setopt($session, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($session, CURLOPT_USERPWD, 'api:'.MAILGUN_KEY);
curl_setopt($session, CURLOPT_POST, true);
curl_setopt($session, CURLOPT_POSTFIELDS, $array_data);
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_ENCODING, 'UTF-8');
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($session);
curl_close($session);
$results = json_decode($response, true);
return $results;
}
I am trying to send a notification email to end users with the following code:
$eml = email address variable
$usrn = user name
$htm = html text generated from mailtext.php with displaytext function
$cust_orderid = parameter,not really important in this case
if ((strlen($eml)>5)&&(isset($eml))&&(!is_null($eml))) {
include('./mailtext.php');
$htm = displaytext($cust_orderid);
require_once('./mailgun.php');
sendmailbymailgun($eml,$usrn,'NOTIFICATIONS','notify#mydomain.com','NOTIFICATION SUBJECT',$htm,'','','');
}
everything works fine, until i have in $eml field multiple email addresses separated with comma.
then i got the following error message:
'to' parameter is not a valid address. please check documentation
i checked the documentation and it tells, that i can have multiple email addresses separated by comma. reference:
mailgun API documentation
some ideas how to solve this problem?
thanks in advance

So after a suggestion of #Igor Ilic i modified the mailgun.php like this:
<?
define('MAILGUN_URL', 'https://api.eu.mailgun.net/v3/mydomain');
define('MAILGUN_KEY', 'xxxxxxxxxxx');
function sendmailbymailgun($to,$toname,$mailfromnane,$mailfrom,$subject,$html,$text,$tag,$replyto){
$array_data = array(
'from'=> $mailfromnane .'<'.$mailfrom.'>',
'to'=> $to,
'subject'=>$subject,
'html'=>$html,
'text'=>$text,
'o:tracking'=>'yes',
'o:tracking-clicks'=>'yes',
'o:tracking-opens'=>'yes',
'o:tag'=>$tag,
'h:Reply-To'=>$replyto
);
$session = curl_init(MAILGUN_URL.'/messages');
curl_setopt($session, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($session, CURLOPT_USERPWD, 'api:'.MAILGUN_KEY);
curl_setopt($session, CURLOPT_POST, true);
curl_setopt($session, CURLOPT_POSTFIELDS, $array_data);
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_ENCODING, 'UTF-8');
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($session);
curl_close($session);
$results = json_decode($response, true);
return $results;
}
?>
the only change is :
'to'=> $to,
instead of:
'to'=>$toname.'<'.$to.'>',
now i am simply ignoring the < > part of the email sending - it's not so pretty with the display name/email address in the email header, but i don't care, it works, even when the email address $eml parameter looks dirty like this: 'email1#gmail.com,,,email2#yahoo.com,,email3#office.com,,'
thanks for the great idea,
problem solved

Related

I am looking for some simple PHP code to send Twilio SMS message (without a framework required)

OK, I know I am a noob but I have gotten by with PHP for a while by just writing code in a text editor. With Twilio samples everything is prefaced with...
// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once '/path/to/vendor/autoload.php';
like they show here..
https://www.twilio.com/docs/sms/send-messages
do I need this framework? I just want to send a single SMS message (or maybe loop through a bunch)
Something to get you started. Replace the ... things.
<?php
$twilio_account_sid = "AC...";
$twilio_auth_token = "2d...";
$twilio_phone_number = "+1...";
$payload = [
'From' => $twilio_phone_number,
'To' => '+1...',
'Body' => 'This is the body of the message'
];
$url = 'https://api.twilio.com/2010-04-01/Accounts/' . $twilio_account_sid . '/Messages.json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, $twilio_account_sid . ':' . $twilio_auth_token);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close ($ch);
var_dump( $status );
var_dump( $response );
?>

how to send email using infobip service

I am now developing a web application and it needs to send emails.
I first used smtp service and for some reason I have chosen infobip.com for emailing service.
It has good documentations on api so I followed the tutorial.
The problem is even though I think I followed all steps I have some error like "bad request"
There is api for sending sms using infobip service.
(https://github.com/pnlinh)
But no api for sending emails.
private $from = "some person";
private $subject = "test subject";
private function setPostData($to, $text)
{
return [
'from' => $this->from,
'to' => (array) $to,
'subject' => $this->subject,
'text' => $text,
];
}
public function testFunction()
{
$header = ['Content-Type:application/json', 'Accept:application/json'];
$postUrl = 'https://api.infobip.com/email/1/send';
$to = 'scar20181228#gmail.com';
$text = 'test email';
$postDataJson = json_encode($this->setPostData($to, $this->subject, $text));
// Set retry time if response is null or empty
$retrytime = 0;
retry_from_here:
$ch = curl_init();
// Setting options
curl_setopt($ch, CURLOPT_URL, $postUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, 'username'.':'.'password');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postDataJson);
// Response of the POST request
$response = curl_exec($ch);
if ($response === '' && $retrytime <= static::RETRY_TIME) {
$retrytime++;
goto retry_from_here;
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$responseBody = json_decode($response);
curl_close($ch);
return [$httpCode, $responseBody];

Codeigniter Plivo PHLO - Curl sending json

I would like to understand why the "HTTPHEADER" option is not interpreted correctly. The sending is going well, but the Plivo server can't read my request which doesn't arrive in JSON.
Below, the helper Codeigniter:
function launchCall($from, $to, $position, $message){
$CI = &get_instance();
$CI->load->config('plivo');
$data = array("from" => $from, "to" => $to, "position" => $position, "message" => $message);
$data_string = json_encode($data);
$url = 'https://phlorunner.plivo.com/v1/account/YYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXX';
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json','Content-Type: application/json', 'Content-Length: ' . strlen($data_string)));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_USERPWD, $CI->config->item('AUTH_ID') . ":" . $CI->config->item('AUTH_TOKEN'));
$result = curl_exec($ch);
return $result;
}
Thank you in advance for your help.
There are no issues with your code. The payload is received fine. The reason your attempt is failing is minor and could be fixed in a jiffy.
The Caller ID (from) needs to be a valid phone number in E.164 phone number format. Add Country code to your Caller ID and your PHLO should work fine.

PHP: CURL sendgrid API V3 authorization

I need a lot of help with curl and sendgrid integration and I wanted to start with the curl statement shown below:
curl -X "GET" "https://api.sendgrid.com/v3/contactdb/recipients" -H "Authorization: basic key" -H "Content-Type: application/json"
Below script gives me an error "message":"request body is invalid"
<?php
$url = 'https://api.sendgrid.com/v3';
$request = $url.'/contactdb/lists';
// Generate curl request
$userid = 'useid';
$userkey= '12345';
$headers = array(
'Authorization' => 'Basic xxxxxxx',
);
$session = curl_init($request);
// Tell curl to use HTTP get
curl_setopt ($session, CURLOPT_POST, FALSE);
// Tell curl that this is the body of the GET
curl_setopt ($session, CURLOPT_POSTFIELDS, $headers);
curl_setopt($session, CURLOPT_USERPWD, $userid.':'.$userkey);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, False);
// Tell PHP not to use SSLv3 (instead opting for TLS)
curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// obtain response
$response = curl_exec($session);
var_dump($response);
curl_close($session);
?>
Eventually, I want to integrate the subscription system from my website to seamlessly update Sendgrid contact lists. If you think there are better ways to achieve this, please feel free to point it out to me as well. Thanks!
Based on your code, try this:
<?php
$url = 'https://api.sendgrid.com/v3/templates';
$request = $url.'/user/profile';
$params = array(
'name' => 'test'
);
$json_post_fields = json_encode($params);
// Generate curl request
$ch = curl_init($request);
$headers = array("Authorization: Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERAGENT, $defined_vars['HTTP_USER_AGENT']);
// Apply the JSON to our curl call
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_post_fields);
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
var_dump($data);
curl_close($ch);
}
?>
Also when trying to debug these kind of API integrations I find it very useful to bind cURL to a local proxy that way I can monitor the HTTP communication between cURL and the API, e.g.,
curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:8888");
If your using Windows and testing locally Fiddler works great for that.
Here's my solution. It is based off too many sources to list.
define("SENDGRID_API_KEY","SG.xxxxxxxxxxxxxxxxxxxxxxxx");
//the 'to' parameter can be either be a single email as a string or an array of emails
function email($to,$subject,$message) {
if (!$to) return;
//start the params
$params=[
'from'=> "yourEmail#address.com",
'fromname'=> "Your From Name",
'subject'=> $subject,
'text'=> preg_replace("/\n\s+/","\n",rtrim(html_entity_decode(strip_tags($message)))),
'html'=> $message,
];
//if we have an array of email addresses, add a to[i] param for each
if (is_array($to)) {
$i=0;
foreach($to as $t) $params['to['.$i++.']']=$t;
//just one email, can add simply like this
} else {
$params['to']=$to;
}
// Generate curl request
$session = curl_init('https://api.sendgrid.com/api/mail.send.json');
// Tell PHP not to use SSLv3 (instead opting for TLS)
curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
curl_setopt($session, CURLOPT_HTTPHEADER, array('Authorization: Bearer '.SENDGRID_API_KEY));
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
//execute and obtain response
$response = curl_exec($session);
curl_close($session);
//no response at all. that's bad!
if (!$response) {
$errorMessage="SENDGRID SENT NO RESPONSE<br>";
} else {
$response=json_decode($response,true);
//wasn't a success
if ($response['message']!='success') {
$errorMessage="SENDGRID SENDING ERROR<br>Error(s): ".implode("<br>",$response['errors']);
}
}
//finish forming error message and save to log
if ($errorMessage) {
$errorMessage.="Subject: ".$subject."<br>To: ";
if (is_array($to)) {
$errorMessage.=implode(",",$to);
//just one email, can add simply like this
} else {
$errorMessage.=$to;
}
yourOwnLoggingFunction($errorMessage);
}
//show full response if needed
// print_r($response);
}
//send to one person
email("test#email.com","The Subject","<h1>The Body</h1><p>Goes here</p>");
//send to multiple people
email(["test1#email.com","test2#email.com"],"The Subject","<h1>The Body</h1><p>Goes here</p>");
<?php
$url = 'https://api.sendgrid.com/v3';
$request = $url.'/contactdb/lists';
// Generate curl request
$userid = 'useid';
$userkey= '12345';
$session = curl_init($request);
// Tell curl to use HTTP get
curl_setopt ($session, CURLOPT_POST, FALSE);
// Tell curl that this is the body of the GET
curl_setopt($session, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ) ;
curl_setopt($session, CURLOPT_USERPWD, $userid.':'.$userkey);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, False);
curl_setopt($session, CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
// Tell PHP not to use SSLv3 (instead opting for TLS)
curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// obtain response
$response = curl_exec($session);
var_dump($response);
curl_close($session);
?>
Solved & working version here

Posting to posterous.com through posterous api

I am using curl and i want to post through posterous api. I am using this method posterous.com/api/newpost
My code is
$url="userid"
$posturl = "posterous.com/api/newpost";
$session = curl_init($posturl);
$postVars = array(
"site_id" => $url,
"body"=>$message
);
curl_setopt($session, CURLOPT_POST, true);
curl_setopt($session, CURLOPT_POSTFIELDS, $postVars);
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($session);
$obj = json_decode($response,true);
curl_close($session);
But I am getting this error
<rsp stat="fail">
<err code="3001" msg="Invalid Posterous email or password" />
</rsp>
Please guide me on this
Thanks
Well you don't actually seem to be sending an email address or password, so I guess that's the problem.
All calls require user authentication
which is done by basic HTTP
authentication with a user's Posterous
email address and password.
You can do it like this:
$user = 'foo#bar.com';
$password = 'foobar';
curl_setopt($session, CURLOPT_USERPWD, $user . ":" . $password);

Categories