I am currently working on a yii2 application and I have integrated wadeshuler/yii2-sendgrid plugin in my application to send emails through it.
I have setup a dynamic template with a template id in my sendgrid account. Here is the code I am using to test sendgrid integration with my app.
public function actionTest()
{
$mailer = Yii::$app->mailer;
$message = $mailer->compose()
->setTo('umair#****.com') // or just $user->email
->setFrom(['alerts#example.com' => 'Alerts'])
->setReplyTo('noreply#example.com')
->setSubject('Hey -username-, Read This Email')
->setHtmlBody('Dear -username-,<br><br>My HTML message here')
->setTextBody('Dear -username-,\n\nMy Text message here')
->setTemplateId('******')
->addSubstitution('-username-', 'Umair Ashraf')
->send();
if ($message === true) {
echo 'Success!';
echo '<pre>' . print_r($mailer->getRawResponses(), true) . '</pre>';
} else {
echo 'Error!<br>';
echo '<pre>' . print_r($mailer, true) . '</pre>';
echo '<pre>' . print_r($mailer->getErrors(), true) . '</pre>';
}
}
Here is the response code printed
Error!
{"code":400,"headers":["HTTP/1.1 400 Bad Request","Server: nginx","Date: Fri, 27 Dec 2019 13:31:27 GMT","Content-Type: application/json","Content-Length: 238","Connection: keep-alive","Access-Control-Allow-Origin: https://sendgrid.api-docs.io","Access-Control-Allow-Methods: POST","Access-Control-Allow-Headers: Authorization, Content-Type, On-behalf-of, x-sg-elas-acl","Access-Control-Max-Age: 600","X-No-CORS-Reason: https://sendgrid.com/docs/Classroom/Basics/API/cors.html","",""],"body":"{\"errors\":[{\"message\":\"Substitutions may not be used with dynamic templating\",\"field\":\"personalizations.0.substitutions\",\"help\":\"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.personalizations.substitutions\"}]}"}
Array
(
[0] => Bad Request!
)
As you can see it says that substitutions may not be used with dynamic templating, but I will be needing to substitute these variable inorder to use templates correclty. How to fix this using the code?
I had to remove wadeshuler/yii2-sendgrid plugin as it didn't support the latest features and updates in the sendgrid liberary. I installed the latest sendgrid plugin. I also made a component named SendGridManager to route all the emails through it in my application.
Here is my function inside the component SendgridManager
public function email($from , $to, $substitution, $templateId, $senderName = NULL,
$toName = NULL, $attachment = NULL)
{
$response = '';
$email = new \SendGrid\Mail\Mail();
$email->setFrom($from,$senderName);
$email->addTo($to , $toName, $substitution);
$email->setTemplateId($templateId);
if(!empty($attachment))
{
$email->addAttachment(
$attachment
);
}
$sendgrid = new \SendGrid($this->apiKey);
try {
$response = $sendgrid->send($email);
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage(). "\n";
}
return $response;
}
Related
I am using sendgrid api v3. Everything works fine on my localserver with core php and now i move my code on server with codeigniter framework. It shows me following error.
Fatal error: Call to undefined method Sendgrid::send() in /var/www/html/adihex/application/helpers/sendgrid_helper.php on line 19
Here is my code
<?php
require_once FCPATH . 'sendgrid-php/sendgrid-php.php';
function send_mail()
{
$template_id = '********************************';
$api_key = '*************************************';
// echo '<pre>';
$email = new \SendGrid\Mail\Mail();
$email->setFrom("test#example.com", "Example User");
$email->setSubject("Sending with Twilio SendGrid is Fun");
$email->addTo("singhrobin1238014#gmail.com", "Example User");
$email->setTemplateId($template_id);
$email->addDynamicTemplateDatas([
'heading' => 'Welcome to Adihex',
]);
$sendgrid = new \SendGrid($api_key);
try {
$response = $sendgrid->send($email);
print $response->statusCode() . "\n";
print_r($response->headers());
print $response->body() . "\n";
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage() . "\n";
}
}
Please guide me where i am wrong.
Any solution appreciated!
Although its late but it might help someone ,
You might be having Multiple Classes with same name , SendGrid In this case the script is searching for send function in someother Class with same name,
Im working on an application where I've created a user registration system. So when a user registers an email is sent to the account, Im using an email class to send email. Before using sendgrid I was using phpmailer and it was working perfectly fine in this format, but it doesn't works with sendgrid.
This is the code
<?php
class email {
public function sendEmail($name, $email, $url, $type, $subject){
require '../../vendor/autoload.php'; // If you're using Composer (recommended)
$email = new \SendGrid\Mail\Mail();
$email->setFrom("mymail#gmail.com", "Example User");
$email->setSubject($subject);
$email->addTo($email, $name);
if($type === "CONFIRM"){
$email->addContent(
'text/html', 'CONFIRM MESSAGE'
);
} else if($type === "FORGOT"){
$email->addContent(
'text/html', 'FORGOT MESSAGE'
);
}
$apiKey = 'api_key';
$sendgrid = new \SendGrid($apiKey);
try {
$response = $sendgrid->send($email);
print $response->statusCode() . "\n";
print_r($response->headers());
print $response->body() . "\n";
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage() ."\n";
}
}
}
?>
So when i use this code without if and else for '$type', it works completely fine, but does not works with if else and the page loading never ends!
Some help would be appreciated!!
Im working on an application where I've created a user registration system. So when a user registers an email is sent to the account, Im using an email class to send email. Before using sendgrid I was using phpmailer and it was working perfectly fine in this format, but it doesn't works with sendgrid.
So when i use this code without if and else for '$type', it works completely fine, but does not works with if else and the page loading never ends!
Some help would be appreciated!!
This is the code
<?php
class email {
public function sendEmail($name, $email, $url, $type, $subject){
require '../../vendor/autoload.php'; // If you're using Composer (recommended)
$email = new \SendGrid\Mail\Mail();
$email->setFrom("mymail#gmail.com", "Example User");
$email->setSubject($subject);
$email->addTo($email, $name);
if($type === "CONFIRM"){
$email->addContent(
'text/html', 'CONFIRM MESSAGE'
);
} else if($type === "FORGOT"){
$email->addContent(
'text/html', 'FORGOT MESSAGE'
);
}
$apiKey = 'api_key';
$sendgrid = new \SendGrid($apiKey);
try {
$response = $sendgrid->send($email);
print $response->statusCode() . "\n";
print_r($response->headers());
print $response->body() . "\n";
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage() ."\n";
}
}
}
?>
I have the code below which is from sendgrid for sending an email with my API key but I cannot get it to work as it displays
error Fatal error: Uncaught Error: Call to a member function send() on
string in ...
I have install composer as required
It seems, However, $sendgrid->send($email) doesn't actually return anything, so $mail is an empty variable.
Any idea on how to resolve this.
Api link source.
<?php
// https://sendgrid.com/docs/API_Reference/index.html
// using SendGrid's PHP Library
// https://github.com/sendgrid/sendgrid-php
require 'vendor/autoload.php'; // If you're using Composer (recommended)
// Comment out the above line if not using Composer
// require("./sendgrid-php.php");
// If not using Composer, uncomment the above line
$email = new \SendGrid\Mail\Mail();
$email->setFrom("test#example.com", "Example User");
$email->setSubject("Sending with SendGrid is Fun");
$email->addTo("test#example.com", "Example User");
$email->addContent(
"text/plain", "and easy to do anywhere, even with PHP"
);
$email->addContent(
"text/html", "<strong>and easy to do anywhere, even with PHP</strong>"
);
//$sendgrid = new \SendGrid(getenv('my api goes here'));
$sendgrid = 'my api goes here';
try {
$response = $sendgrid->send($email);
print $response->statusCode() . "\n";
print_r($response->headers());
print $response->body() . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
You are trying to call a function on a string.
$sendgrid = 'my api goes here';
And later:
$response = $sendgrid->send($email);
What I think you meant:
$response = $email->send($email);
I am implementing twilio in my laravel 5 application. To use it in the framework I use aloha/laravel-twilio integration.
Sending a valid request with test-credentials works fine. I have problems when I want to implement an error-handling.
For some reason the catch does not get the error, which results in a crash of the app. The error seems to be in the twilio-sdk if I read the error message correctly.
Here is what I've done so far:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
use Aloha\Twilio\TwilioInterface;
class Activation extends Model {
protected $fillable = array( 'a', 'b', 'c');
public static function send() {
// Testaccount
// $toNumber = '+15005550006'; // valid number; works fine
$toNumber = '+15005550001'; // #todo will throw an exeption, and breaks the app
try {
\Twilio::message( $toNumber, 'Pink Elephants and Happy Rainbows');
} catch ( Services_Twilio_RestException $e ) {
elog( 'EACT', $e->getMessage( ) , __FUNCTION__ ); // this is not called when an twilio error occurs
}
}
}
This results in the following error:
Whoops, looks like something went wrong.
Services_Twilio_RestException in /path/to/my/laravel/vendor/twilio/sdk/Services/Twilio.php line 297
Exception_message: The 'To' number +15005550001 is not a valid phone number.
From the documentation this error (not valid phone numer) shall be thrown, but I should have a possiblity to catch and process it. Currently, this does not work. I do not get the error catched...
How can I get the twilio-errors catched and processed?
The class is in a namespace, so I have to reference the absolut class exception - \Services_Twilio_RestException - in the catch .
It works with this code:
try {
\Twilio::message( $toNumber, 'Pink Elephants and Happy Rainbows');
} catch ( \Services_Twilio_RestException $e ) {
elog( 'EACT', $e->getMessage( ) , __FUNCTION__ );
}
See below which is valid as of today. TwilioException is not valid and neither is Services_Twilio_RestException. You should use Exception instead.
UPDATE
You need to import Twilio\Exceptions\TwilioException for TwilioException to work.
My use case is I had to send to a database of numbers and not have an invalid phone number break my script. We did some work-around a month or two ago which involved logging when a message was sent and had a cron job checking where we left off every two minutes... not efficient when you're sending tens of thousands of text messages.
require_once '../Twilio/autoload.php'; // Loads the library
use Twilio\Rest\Client;
//some test fail numbers
$arr = array(1234567890,"11855976lend1",321619819815,198198195616516);
/* ==================================================================================
//create a function to send SMS using copilot (uses an SID instead of a phone number)
================================================================================*/
function sendSMS($to){
// Download the PHP helper library from twilio.com/docs/php/install
// These vars are your accountSid and authToken from twilio.com/user/account
$account_sid = 'xxx';
$auth_token = 'xxx';
$client = new Client($account_sid, $auth_token);
//this nifty little try/catch will save us pain when we encounter bad phone numbers
try{
$client->messages->create(
$to,
array(
'messagingServiceSid' => "MGxxx",
'body' => "This is the body we're sending."
)
);
//sent successfully
echo "sent to $to successfully<br>";
}catch(Exception $e){
echo $e->getCode() . ' : ' . $e->getMessage()."<br>";
}
}
foreach($arr as &$value){
sendSMS($value);
}
//remember to unset the pointer so you don't run into issues if re-using
unset($value);
Today (19-May-2017) the code is like this :
// Step 1: set our AccountSid and AuthToken from https://twilio.com/console
$AccountSid = "XXX";
$AuthToken = "XXX";
$client = new Client($AccountSid, $AuthToken);
try {
$sms = $client->account->messages->create(
// the number we are sending to - Any phone number
$number,
array(
// Step 2: Change the 'From' number below to be a valid Twilio number
// that you've purchased
'from' => "+XXXXXXXXXXX",
// the sms body
'body' => $sms
)
);
// Display a confirmation message on the screen
echo "Sent message to $name";
} catch (TwilioException $e) {
die( $e->getCode() . ' : ' . $e->getMessage() );
}
This is what worked for me:
$twilioCli = new \Twilio\Rest\Client(config('app.twilioAccountSID'), config('app.twilioAuthToken'));
try {
$twilioCli->messages->create(
$formattedToNum,
[
'from' => config('app.twilioFromNumber'),
'body' => "sms body goes here"
]
);
}
catch (\Twilio\Exceptions\RestException $e) {
echo "Error sending SMS: ".$e->getCode() . ' : ' . $e->getMessage()."\n";
}