Send Dynamic PHP HTML With Sendgrid Web API - php

I'd like to use Sendgrid WebAPI preferably without SMTP or Swiftmailer using the code below. Is it possibly to pass an entire dynamic webpage to the 'html' $params array without creating a long string variable and needing to escape every quote and echo each variable? Each email varies significantly so Sendgrid's template/mailmerge options will not work for me. Thanks!
Here's a simple html example (mine has much more dynamic content):
<html>
<head></head>
<body>
<p>Hi I'm <?php echo $name; ?>!<br>
<span style="color: #999999; font-size: 11px;">How are you?</span><br>
</p>
</body>
</html>
$url = 'http://sendgrid.com/';
$user = 'USERNAME';
$pass = 'PASSWORD';
$params = array(
'api_user' => $user,
'api_key' => $pass,
'to' => 'example3#sendgrid.com',
'subject' => 'testing from curl',
'html' => 'testing body',
'text' => 'testing body',
'from' => 'example#sendgrid.com',
);
$request = $url.'api/mail.send.json';
// Generate curl request
$session = curl_init($request);
// 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);
// obtain response
$response = curl_exec($session);
curl_close($session);
// print everything out
print_r($response);

The best way to generate the HTML you need would be to use a template engine like Smarty. So in your example, somewhere above actually sending the email, you would do something like:
include('Smarty.class.php');
$smarty = new Smarty;
$smarty->assign('name', 'Swift');
$smarty->assign('name', 'SendGrid');
$smarty->assign('address', '123 Broadway');
// Store it in a variable
$emailBody = $smarty->fetch('some_dynamic_template.tpl');
And then when you actually need to send the email with the new dynamic HTML body:
....
$params = array(
'api_user' => $user,
'api_key' => $pass,
'to' => 'example3#sendgrid.com',
'subject' => 'testing from curl',
'html' => $emailBody,
'from' => 'example#sendgrid.com',
);
....

In the same case SMTP API is easier by using substitution tags, more details : http://sendgrid.com/docs/API_Reference/SMTP_API/substitution_tags.html

Related

Gmail show Moved Permanently in mail detail

I send an email by php code.
I use api Aws\Ses\SesClient to send email.
This is my code:
function sendOrderInfoToCustomer($sTo){
$ch = curl_init($this->sMainUrl."/content_email_order_info.php?orderID=".$this->iOrderID);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$sContentOrderInfo = curl_exec($ch);
curl_close($ch);
$sSubject = $this->oPublicFunction->getSiteName()." [".$this->oPublicFunction->parseFormatTime("d/m/Y H:i A",time())."]";
$this->oPublicFunction->sendMailAWS($sTo,$sSubject,$sContentOrderInfo);
}
function sendMailAWS($sTo,$sSubject,$sBody){
global $aws_access_key, $aws_secret_access_key, $aws_from;
$client = Aws\Ses\SesClient::factory(array(
'version'=> 'latest',
'region' => 'us-east-1',
'credentials' => array(
'key' => $aws_access_key,
'secret' => $aws_secret_access_key
)
));
$request = array();
$request['Source'] = $aws_from;
$request['Destination']['ToAddresses'] = array($sTo);
$request['Message']['Subject']['Data'] = $sSubject;
$request['Message']['Body']['Html']['Data'] = $sBody;
try {
$result = $client->sendEmail($request);
$messageId = $result->get('MessageId');
//echo("Email sent! Message ID: $messageId"."\n");
} catch (Exception $e) {
echo("The email was not sent. Error message: ");
echo($e->getMessage()."\n");
}
}
Send mail is success. But I check mail on gmail I see email is not good.
Please help me fix it.
This is not a result of email, it's actually the content that your CURL is getting from your own server when building the message body. You probably just have to tell curl to follow redirects:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
You may have a more serious problem here, however. Your app (generally) shouldn't be using web requests to itself. The email content should be created via an internal method call that renders the order template, and not by calling a web page. Here, it appears that you've opened the order detail page to the entire web. I.e., anybody on the web can hit content_email_order_info.php?orderID=123 and get the details for any order because there's no authentication going on there. This could be a very serious security breach.

How do I include in-line images when sending with Mailgun API and PHP cURL

I have been searching SO for clues on how to send in-line images in my emails using the Mailgun API and standard PHP cURL - not with the Mailgun SDK and had no luck, so I've resorted to posting the question.
This is my code so far:
$url = 'https://api:**my-key**#api.eu.mailgun.net/v3/**my-domain.com**/messages';
$from = 'Admin < admin#my-domain.com >';
$to = 'Excite User < user#somewhere.com >';
$subject= 'Excite Stuff In Here';
$body = '<html>
<img src="cid:logo_sml.png">
<p>Testing Mailgun API with inline images</p>
</html>';
$text = strip_tags( nl2br($body) );
$tag = 'Test';
$inline = ['inline' => realpath('../includes/images/logo_sml.png')];
// parameters of message
$params = [
'from' => $from,
'to' => $to,
'subject' => $subject,
'text' => $text,
'html' => $body,
'inline' => json_encode($inline),
'o:tag' => $tag
];
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $params );
$data_results = curl_exec($curl);
$response = json_decode($data_results);
curl_close($curl);
The email is being sent without any error messages but is received with no images - either inline or as an attachment. Where am I going wrong?
I raised a ticket with Mailgun Support and Marco has responded with a solution which I thought I would share:
$inline = curl_file_create(realpath('../includes/images/logo_sml.png'));
...
'inline' => $inline,
curl_file_create — Creates a CURL file object to attach the image. The rest of the code is unchanged.

How to send an sms to a phone number using php- Codeigniter?

How to send an sms to a phone number using php- Codeigniter?
We have an sms-gateway-provider and I have a user-id, password and api-url. What I wanted to know is, how would I use these in a codeigniter framework, could I get a sample codes? I just wanted the proper codes to achieve this in Codeigniter.
There is simple sms helper available for codeigniter
Copy below file from github as sendsms_helper.php in /application/helpers/
https://github.com/SpringEdgeIndia/codeigniter-sms-api/
Usage:
Load sendsms helper as $this->load->helper('sendsms_helper');
Call sendsms function Ex. sendsms( '919918xxxxxx', 'test message' );
its a simple script
$sending = http_post("your_domain", 80, "/sendsms", array("Username" => $uname, "PIN" => $password, "SendTo" => $Phone, "Message" => $usermessage));
and bingo
you must use cURL for better security in CodeIgniter. this function works fine for sending SMS.
function sms_code_send($number='',$message='')
{
$username = 'username';
$password = '*******';
$originator = 'sender name';
$message = 'Welcom to ......, your activation code is : '.$message;
//set POST variables
$url = 'http://exmaple.com/bulksms/go?';
$fields = array(
'username' => urlencode($username),
'password' => urlencode($password),
'originator' => urlencode($originator),
'phone' => urlencode($number),
'msgtext' => urlencode($message)
);
$fields_string = '';
//url-ify the data for the POST
foreach($fields as $key=>$value)
{
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
return $result;
}

SendGrid - Curl php external file attachment broken

I'm using SendGrid for a customer project with curl method.
All works fine but the(ir) file(s) attached on my email sending with SendGrid are broken.
Here is my code :
$documentList = array(
"DOC1.php" => "http://www.customerdomain.com/my/path/where/my/attachment/file/is/myfile.pdf"
);
$params = array(
'api_user' => $user;
'api_key' => $pass,
'x-smtpapi' => json_encode($json_string),
'from' => $from,
'to' => $to,
'subject' => $subject,
'html' => $mailHtml,
'text' => $mailText
);
if(count($documentList)>0){
foreach($documentList as $fileName=>$documentPath){
$params['files['.$fileName.']'] = $documentPath;
}
}
$request = $url.'api/mail.send.json';
// Generate curl request
$session = curl_init($request);
// 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);
// obtain response
$response = curl_exec($session);
curl_close($session);
When I don't have extension file on my key of array, I've a text file containing the related value.
I think I'm not alone to have this problem, well, if you've any idea to solve this problem, thanks for your help !
The issue you're experiencing is because you are giving SendGrid a URL for file, rather than the file itself, and SendGrid's API needs the file.
To get your code to work, simply change the $documentList variable to:
$documentList = array(
"DOC1.pdf" => "#" . realpath("/path/where/my/attachment/file/is/myfile.pdf")
);
Instructions on this kind of file upload can be found in this StackOverflow Question, but you might otherwise want to use curl_file_create, to do this.
However, perhaps the best/easiest way to do this is to use SendGrid's PHP Library which makes sending attachments, trivially simple.:
require("path/to/sendgrid-php/sendgrid-php.php");
$sendgrid = new SendGrid('username', 'password');
$email = new SendGrid\Email();
$email->addTo('foo#bar.com')->
setFrom('me#bar.com')->
setSubject('Subject goes here')->
setText('Hello World!')->
setHtml('<strong>Hello World!</strong>')
addAttachment("../path/to/file.txt");
$sendgrid->send($email);
My initial issue was because the path is an autogenerated link and that's why I didn't use an url than realpath.
Anyway, I changed my code and I use now the realpath with mimetype mentioned after the file realpath (and # before).
It seems work fine now.
I'll like to thank you for your help.
Regards

Send parameters to a URL and get output from that page

I have 2 pages say abc.php and def.php. When abc.php sends 2 values [id and name] to def.php, it shows a message "Value received". Now how can I send those 2 values to def.php without using form in abc.php and get the "Value received" message from def.php? I can't use form because when user frequently visits the abc.php file, the script should automatically work and get the message "Value received" from def.php. Please see my example code:
abc.php:
<?php
$id="123";
$name="blahblah";
//need to send the value to def.php & get value from that page
// echo $value=Print the "Value received" msg from def.php;
?>
def.php:
<?php
$id=$_GET['id'];
$name=$_GET['name'];
if(!is_null($id)&&!is_null($name))
{ echo "Value received";}
else{echo "Not ok";}
?>
Is there any kind heart who can help me solve the issue?
First make up your mind : do you want GET or POST parameters.
Your script currently expects them to be GET parameters, so you can simply call it (provided that URL wrappers are enabled anyway) using :
$f = file_get_contents('http://your.domain/def.php?id=123&name=blahblah');
To use the curl examples posted here in other answers you'll have to alter your script to use $_POST instead of $_GET.
You can try without cURL (I havent tried though):
Copy pasted from : POSTing data without cURL extension
// Your POST data
$data = http_build_query(array(
'param1' => 'data1',
'param2' => 'data2'
));
// Create HTTP stream context
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $data
)
));
// Make POST request
$response = file_get_contents('http://example.com', false, $context);
Taken from the examples page of php.net:
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "example.com/abc.php");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
Edit: To send parameters
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( tch, CURLOPT_POSTFIELDS, array('var1=foo', 'var2=bar'));
use CURL or Zend_Http_Client.
<?php
$method = 'GET'; //change to 'POST' for post method
$url = 'http://localhost/browse/';
$data = array(
'manufacturer' => 'kraft',
'packaging_type' => 'bag'
);
if ($method == 'POST'){
//Make POST request
$data = http_build_query($data);
$context = stream_context_create(array(
'http' => array(
'method' => "$method",
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $data)
)
);
$response = file_get_contents($url, false, $context);
}
else {
// Make GET request
$data = http_build_query($data, '', '&');
$response = file_get_contents($url."?".$data, false);
}
echo $response;
?>
get inspired by trix's answer, I decided to extend that code to cater for both GET and POST method.

Categories