How to pass dynamic data to email template of sendgrid? - php

I have integrated sendgrid in Laravel and I managed to send the email template of sendgrid in emails but I am not able to replace the content in the email templates. I am using Sendgrid Web API V3.
I followed the steps given in the below link but it is not replacing the variables in template with my dynamic data.
Link: How to pass dynamic data to email template desgined on sendgrid webapp ? :-| Sendgrid
Here is code
$sg = new \SendGrid('API_KEY');
$request_body = json_decode('{
"personalizations":[
{
"to":[
{
"email":"example#example.com"
}
],
"subject":"Hello World from the SendGrid PHP Library!"
}
],
"from":{
"email":"from#example.com"
},
"content":[
{
"type":"text/html",
"value":"<html><body> -name- </body></html>"
}
],
"sub": {
"-name-": ["Alice"]
},
"template_id":"xxxxxx-xxx-xxxxxxxx"
}');
$mailresponse = $sg->client->mail()->send()->post($request_body);
echo $mailresponse->statusCode();
echo $mailresponse->body();
echo $mailresponse->headers();
Please help.

This works perfectly and is much simpler than the solutions already posted:
$email = new \SendGrid\Mail\Mail();
$email->setFrom( "from#example.com", "Some guy" );
$email->addTo( "to#example.com", "Another guy" );
$email->setTemplateId(
new \SendGrid\Mail\TemplateId( TEMPLATE_ID )
);
// === Here comes the dynamic template data! ===
$email->addDynamicTemplateDatas( [
'variable1' => 'Some stuff',
'templatesRock' => 'They sure do!'
] );
$sendgrid = new \SendGrid( API_KEY );
$response = $sendgrid->send( $email );

I have overcome this issue by using another way. Below is code that is working fine. May be help some one..
//create mail object
$mail = new \SendGrid\Mail();
//set from
$from = new \SendGrid\Email("SENDER NAME", "SENDER EMAIL");
$mail->setFrom($from);
//set personalization
$personalization = new \SendGrid\Personalization();
$to = new \SendGrid\Email("RECEIVER NAME", "RECEIVER EMAIL");
$personalization->addTo($to);
$personalization->setSubject("SUBJECT");
//add substitutions (Dynamic value to be change in template)
$personalization->addSubstitution(':name', "Any");
$mail->addPersonalization($personalization);
$mail->setTemplateId("TEMPLATE_ID");
//send email
$sg = new \SendGrid("API_KEY");
$response = $sg->client->mail()->send()->post($mail);

It's a little bit late but maybe this can help some one to. I faced the same problem and #bwest answer helped me to solve it:
The substitutions values cannot be an array and the should look like:
`"personalizations":[{
"to":[{
"email":"example#example.com"
}],
"subject":"Hello World from the SendGrid PHP Library!",
"substitutions": {
"-name-": "Alice"
}
}
],
...

IN JAVA use:
Personalization personalization = new Personalization();
and its methods for sending the dynamic data to sendgrid template and use {{}}
for receiving the data on sendgrid.

Related

Updating an email's subject using Microsoft Graph in PHP

Here's my current code:
require_once '/pathtovendor/vendor/autoload.php';
use Microsoft\Graph\Graph;
use Microsoft\Graph\Model;
use Microsoft\Graph\Http\GraphRequest;
$access_token = "My valid access token";
$graph = new Graph();
$graph->setAccessToken($access_token);
$reply = array( "Comment" => "My reply" );
$message_id = "Valid message ID";
if($graph->createRequest("POST", "/me/messages/".$message_id."/reply")
->attachBody($reply)
->execute()){
// I can get to this part OK. Message is replied to.
//This code doesn't work
$graph->createRequest("PATCH", "/me/messages/".$message_id)
->attachBody(array( "Subject" => "New Subject" ))
->execute();
}
I can run GET and POST requests which work, but I can't get PATCH to work this way. It continues to throw a 500 Internal Server Error. Any help is appreciated.
This is only supported on draft messages. From the documentation:
subject | String |
The subject of the message. Updatable only if isDraft = true.
The following properties can only be updated in draft messages:
bccRecipients
body
ccRecipients
internetMessageId
replyTo
sender
subject
toRecipients
from

How to send email via SMTP using MailSo library (PHP)

I have a hard time to send multipart MIME message via SMTP using PHP library called MailSo. Provided two examples are limited. No word on how to create headers, message body, multipart MIME message itself and then send it.
Current webmail (Rainloop) is running on MailSo and I want to avoid using 3rd party library on top of MailSo. Going forward all email actions are stored in the Rainloop Actions.php file.
Based on that to create multipart MIME message I should to create $oMessage object (\MailSo\Mime\Message) and I'm able partially do that like to add subject, message ID, custom headers, message body text but going further I'm not able to set MIME boundaries (to store original message body as a boundary as well additional content type as text/plain) not talking about sending $oMessage object via SMTP.
Here is my test code so far:
include 'lib/MailSo/MailSo.php';
echo '<pre>';
$oLogger = \MailSo\Log\Logger::SingletonInstance()
->Add(\MailSo\Log\Drivers\Inline::NewInstance("\r\n", true))
;
$sToEmails = 'Me As Tester <tester#test.com>';
$oToEmails = \MailSo\Mime\EmailCollection::NewInstance($sToEmails);
$sFromEmails = 'Baba Ganush <no-replay#test.com>';
$oFromEmails = \MailSo\Mime\Email::NewInstance($sFromEmails);
$oMessage = \MailSo\Mime\Message::NewInstance();
$oMessage->RegenerateMessageId();
$oMessage->SetXMailer('RainLoop/1.0.0');
$oMessage->SetCustomHeader('test-header','test-header-value');
$oMessage->setSubject("Test message");
$oMessage->AddText('Generated message body goes here...');
$oMessage->SetFrom($oFromEmails);
$oMessage->SetTo($oToEmails);
$oLogger->WriteDump($oMessage);
Well, I have figured out how to send an email message created using MailSo library (w/o any attachments for now)
Example code below
if($oMessage){
$rMessageStream = \MailSo\Base\ResourceRegistry::CreateMemoryResource();
$iMessageStreamSize = \MailSo\Base\Utils::MultipleStreamWriter($oMessage->ToStream(true), array($rMessageStream), 8192, true, true, true);
}
$aToCollection = $oMessage->GetTo();
if ($aToCollection && $oFrom)
{
$sRawBody = #stream_get_contents($rMessageStream);
if (!empty($sRawBody))
{
$sMailTo = trim($aToCollection->ToString(true));
$sMailSubject = trim($oMessage->GetSubject());
$sMailSubject = 0 === strlen($sMailSubject) ? '' : \MailSo\Base\Utils::EncodeUnencodedValue(\MailSo\Base\Enumerations\Encoding::BASE64_SHORT, $sMailSubject);
$sMailHeaders = $sMailBody = '';
list($sMailHeaders, $sMailBody) = explode("\r\n\r\n", $sRawBody, 2);
unset($sRawBody);
$sMailHeaders = \MailSo\Base\Utils::RemoveHeaderFromHeaders($sMailHeaders, array(\MailSo\Mime\Enumerations\Header::TO_,\MailSo\Mime\Enumerations\Header::SUBJECT));
mail($sMailTo, $sMailSubject, $sMailBody, $sMailHeaders);
}
}

Mandrill PHP library - FROM field

How can I set a proper FROM field for the PHP Mandrill library?
In Java, I can use:
from = "Some Description <noreply#domain.com>";
If I try the same in PHP, I get an error:
Validation error: {"message":{"from_email":"The username portion of the email address is invalid (the portion before the #: Some Description
Only emails with FROMs like this get through:
$from = "noreply#domain.com";
In case it matters, here's how I send an email:
$from = "Some Description <noreply#domain.com>";
$message = array("subject" => $aSubject, "from_email" => $from, "html" => $aBody, "to" => $to);
$response = $mandrill->messages->send($message, $async = false, $ip_pool = null, $send_at = null);
If you read the documentation https://mandrillapp.com/api/docs/messages.html it has two parameters in request
from_email and from_name when we pass
$from = "Name <email>",
It is not accepted by mandrill hence it throws error , To pass a name you need to pass from_name with name value.

Why it takes so long to send multiple emails with Sendgrid?

I have a sport betting tips website and on every tip that i publish i send an email to every user (about 700 users in total) with SendGrid. The problem comes with the delivery time. The email is delayed even half an hour from the time of send.
Does anyone know why and how could i fix it?
I am sending it with SMTP.
Here is some of my code:
$catre = array();
$subiect = $mailPronostic['subiect'];
$titlu = $mailPronostic['titlu'];
$text = $mailPronostic['text'];
$data = new DateTime($this->_dataPronostic);
foreach($users as $user){
array_push($catre, $user->_emailUser);
}
$data = urlencode($data->format("d-m-Y H:i"));
$echipe = urlencode($this->_gazdaPronostic." vs ".$this->_oaspetePronostic);
$pronostic = urlencode($predictii[$this->_textPronostic]);
$cota = $this->_cotaPronostic;
$mesaj = file_get_contents("http://plivetips.com/mailFiles/mailPronostic.php?text=".urlencode($text)."&titlu=".urlencode($titlu)."&data=$data&echipe=$echipe&pronostic=$pronostic&cota=$cota");
//return mail(null, $subiect, $mesaj, $header);
$from = array('staff#plivetips.com' => 'PLIVEtips');
$to = $catre;
$subject = "PLIVEtips Tip";
$username = 'user';
$password = 'pass';
$transport = Swift_SmtpTransport::newInstance('smtp.sendgrid.net', 587);
$transport->setUsername($username);
$transport->setPassword($password);
$swift = Swift_Mailer::newInstance($transport);
$message = new Swift_Message($subject);
$message->setFrom($from);
$message->setBody($mesaj, 'text/html');
$numSent = 0;
foreach ($to as $address => $name)
{
if (is_int($address)) {
$message->setTo($name);
} else {
$message->setTo(array($address => $name));
}
$numSent += $swift->send($message, $failures);
}
Thx.
how long does the script take to run? I have a feeling the script is taking a long time. If that's the case, I think it is because you are opening a connection for each message.
With SendGrid, you can send a message to 1000 recipients with one connection by using the X-SMTPAPI header to define the recipients. The easiest way to do this to use the official sendgrid-php library and use the setTos method.
Recipients added to the X-SMTPAPI header will each be sent a unique email. Basically SendGrid's servers will perform a mail merge. It doesn't look like your email content varies with each user, but if it does, then you may use substitution tags in the header to specify custom data per recipient.
If you don't want to use sendgrid-php, you can see how to build the header in this example.

PHP Twilio App - Including SMS file breaks Foreach loop

I cant figure this out so I'm hoping you can lend a hand.
I am creating a twilio app, and I'm including this entire file in a foreach loop. But it keeps breaking my loop and wont continue after it runs.
It works great, but the foreach this is included inside of will not continue after it runs.
Any ideas?
Thanks,
Nick
<?php
//shorten the URL
$tinyurl = file_get_contents("http://tinyurl.com/api-create.php?url=".$ebay_url);
// Include the PHP TwilioRest library
require "twilio/twilio.php";
// Twilio REST API version
$ApiVersion = "2010-04-01";
// Set our AccountSid and AuthToken
$AccountSid = "removed";
$AuthToken = "removed";
// Instantiate a new Twilio Rest Client
$client = new TwilioRestClient($AccountSid, $AuthToken);
// make an associative array of server admins
$people = array(
"removed"=>"Nick",
//"4158675310"=>"Helen",
//"4158675311"=>"Virgil",
);
// Iterate over all our server admins
foreach ($people as $number => $name) {
// Send a new outgoinging SMS by POST'ing to the SMS resource */
// YYY-YYY-YYYY must be a Twilio validated phone number
$response = $client->request("/$ApiVersion/Accounts/$AccountSid/SMS/Messages",
"POST", array(
"To" => $number,
"From" => 'removed',
"Body" => 'Alert! '.$title.' found for '. $price. '. View the item here: '.$tinyurl,
));
if($response->IsError)
echo "Error: {$response->ErrorMessage}\n";
else
echo "Sent message to: {$response->ResponseXml->SMSMessage->To}\n";
}
?>
I think the problem is that you're doing a require inside the for loop. There are objects defined in that twilio library so the second time you require it, the classes get defined again and this throws an error.
If you have error_reporting(E_ALL) set then you'll see an exception to that effect in your output.
I would either change it to a require_once or move it out of the for loop.
I hope that helps.

Categories