Call to a member function sendEmail() on null - php

I am using the AWS example to call the AWS SDK for PHP. When converting the code to a function I get the following error: Uncaught Error: Call to a member function sendEmail()
line 41 seems to be the issue: $result = $SesClient->sendEmail([
I have tried removing the result variable and commenting out its usage
When I run the code and its not a function its working fine, I am not sure what I am doing wrong here, and I am sure it could be a simple error.
Thanks for the help in advance
<?php
// If necessary, modify the path in the require statement below to refer to the
// location of your Composer autoload.php file.
require '/vendor/autoload.php';
use Aws\Ses\SesClient;
use Aws\Exception\AwsException;
// Create an SesClient. Change the value of the region parameter if you're
// using an AWS Region other than US West (Oregon). Change the value of the
// profile parameter if you want to use a profile in your credentials file
// other than the default.
$SesClient = new SesClient([
'profile' => 'default',
'version' => '2010-12-01',
'region' => 'us-east-1'
]);
function send_email($recipient, $message, $subject){
// Replace sender#example.com with your "From" address.
// This address must be verified with Amazon SES.
$sender_email = 'sender#gmail.com';
// Replace these sample addresses with the addresses of your recipients. If
// your account is still in the sandbox, these addresses must be verified.
// $recipient_emails = ['recipient1#example.com','recipient2#example.com'];
$recipient_emails = [$recipient];
// Specify a configuration set. If you do not want to use a configuration
// set, comment the following variable, and the
// 'ConfigurationSetName' => $configuration_set argument below.
// $configuration_set = 'ConfigSet';
$subject = $subject;
$plaintext_body = $message.PHP_EOL.'This email was sent with Amazon SES using the AWS SDK for PHP.' ;
$html_body = '<h1>'.$message.'</h1>';
$char_set = 'UTF-8';
try {
$result = $SesClient->sendEmail([
'Destination' => [
'ToAddresses' => $recipient_emails,
],
'ReplyToAddresses' => [$sender_email],
'Source' => $sender_email,
'Message' => [
'Body' => [
'Html' => [
'Charset' => $char_set,
'Data' => $html_body,
],
'Text' => [
'Charset' => $char_set,
'Data' => $plaintext_body,
],
],
'Subject' => [
'Charset' => $char_set,
'Data' => $subject,
],
],
// If you aren't using a configuration set, comment or delete the
// following line
// 'ConfigurationSetName' => $configuration_set,
]);
$messageId = $result['MessageId'];
echo("Email sent! Message ID: $messageId"."\n");
} catch (AwsException $e) {
// output error message if fails
echo $e->getMessage();
echo("The email was not sent. Error message: ".$e->getAwsErrorMessage()."\n");
echo "\n";
}
return 'success';
}
echo send_email('test#gmail.com', 'test', 'test subject');

Try declaring $SesClient inside of the send_email function

It's working without the function as you've declared $SesClient outside the function. Declare it after function - or pass it to the function via
function function send_email($recipient, $message, $subject, $SesClient) {
/* snip */
}
echo send_email('test#gmail.com', 'test', 'test subject', $SesClient);

Related

AWS SES SMTP email works. AWS SES API does not send email

I am using AWS SES on a website with shared hosting platform (not on AWS)
When I send emails using the SMTP it works perfectly. When I attempt to call and use the API, no email is sent, no error message is received.
There are two reasons I want to use the API instead of SMTP
1) According to Amazon, the API is faster.
2) One of my transactional emails is a reminder to clients to log in, and/or pay their account. SMTP cannot send email to more than 50 (if I am not mistaken). For that reason, I need to call the SendRawEmail.
Please help me with my code to send the email and to implement SendRawEmail
Here is my code:
require ('PHPMailer/PHPMailerAutoload.php');
use Aws\Ses\SesClient;
use Aws\Exception\AwsException;
// Create an SesClient. Change the value of the region parameter if you're
// using an AWS Region other than US West (Oregon). Change the value of the
// profile parameter if you want to use a profile in your credentials file
// other than the default.
$SesClient = new SesClient([
'profile' => 'default',
'version' => '2010-12-01',
'region' => 'eu-central-1'
]);
// Replace sender#example.com with your "From" address.
// This address must be verified with Amazon SES.
$sender_email = 'info#mydomain.com';
// Replace these sample addresses with the addresses of your recipients. If
// your account is still in the sandbox, these addresses must be verified.
$recipient_emails = ['info#example.com'];
// Specify a configuration set. If you do not want to use a configuration
// set, comment the following variable, and the
// 'ConfigurationSetName' => $configuration_set argument below.
//$configuration_set = 'ConfigSet';
$subject = 'Amazon SES test (AWS SDK for PHP)';
$plaintext_body = 'This email was sent with Amazon SES using the AWS SDK for PHP.' ;
$html_body = '<h1>AWS Amazon Simple Email Service Test Email</h1>'.
'<p>This email was sent with <a href="https://aws.amazon.com/ses/">'.
'Amazon SES</a> using the <a href="https://aws.amazon.com/sdk-for-php/">'.
'AWS SDK for PHP</a>.</p>';
$char_set = 'UTF-8';
try {
$result = $SesClient->sendEmail([
'Destination' => [
'ToAddresses' => $recipient_emails,
],
'ReplyToAddresses' => [$sender_email],
'Source' => $sender_email,
'Message' => [
'Body' => [
'Html' => [
'Charset' => $char_set,
'Data' => $html_body,
],
'Text' => [
'Charset' => $char_set,
'Data' => $plaintext_body,
],
],
'Subject' => [
'Charset' => $char_set,
'Data' => $subject,
],
],
// If you aren't using a configuration set, comment or delete the
// following line
'ConfigurationSetName' => $configuration_set,
]);
$messageId = $result['MessageId'];
echo("Email sent! Message ID: $messageId"."\n");
} catch (AwsException $e) {
// output error message if fails
echo $e->getMessage();
echo("The email was not sent. Error message: ".$e->getAwsErrorMessage()."\n");
echo "\n";
}
?>
Check your error log. I had the same issue:
require 'AWS/aws-autoloader.php';
For other SDK uses (such as API calls) you may need to create a .aws folder to include credentials

Override CakeEmail destination globally

Is there an easy way to "override" the destination of an email using CakeEmail?
I have a model method that send an email using this piece of code:
$Email = new CakeEmail();
$Email->config('default');
$sent = $Email->template('new-notification')
->subject('A new notification for you')
->viewVars([
'name' => $foo['User']['name'],
'text' => $foo['Notification']['text'],
)
->emailFormat('html')
->to($foo['User']['email'])
->send();
And this configuration:
class EmailConfig
{
public $default = array(
'host' => 'smtp.server.com',
'port' => 587,
'username' => 'user#domain.com',
'password' => 'pwdAsYouKnow',
'from' => array('noreply#domain.com' => 'Company'),
'transport' => 'Smtp'
);
}
As you can see, I send the email for a dynamically defined user's email.
My objective is when I'm developing locally on my machine, to force every call to ->send() to force a destination like developer#domain.com.
I can easily detect if I'm on development, but I don't know how to force in a "master" way to CakeEmail only send to a defined account overriding the one set on the call.
I already tried to set an
'to' => array('developer#domain.com' => 'Dev'),
inside $default but, no success.
I appreciate any help, thanks!
i'm assuming when you are on local machine you run in debug mode, so you can check if debug mode is on then use that to send to different email
if(Configure::read('debug')){
$emailTo = 'developer#domain.com'
}
else{
$emailTo = $foo['User']['email'];
}
then you just use variable for email address:
$sent = $Email->template('new-notification')
->subject('A new notification for you')
->viewVars([
'name' => $foo['User']['name'],
'text' => $foo['Notification']['text'],
)
->emailFormat('html')
->to($emailTo)
->send();

cakephp 3.2 email with sendgrid issue

I'm having a hard time trying to figure out how to send mails with sendgrid.
this is the code i currently have:
employees controller:
function _sendEmail($id) {
$email = new Email();
try {
$email->from(['coms#me.co' => 'Me'])
->profile('SendGrid')
->to([$id['email'] => $id['full_name']])
->subject("TEST SUBJECT")
->emailFormat("both")
->template('default')
->send('My message');
$this->Flash->success("Message sent.");
} catch (Exception $ex) {
echo 'Exception : ', $ex->getMessage(), "\n";
}
return $this->redirect(['action' => 'index']);
}
I'm working with this plugin I found a few days ago; https://github.com/Iandenh/cakephp-sendgrid... I configured everything as stated in the docs but when I want to send the mail, nothing happens, the function flashes the success message and makes the redirection, but no email is sent.
This is the email transport in the app.php
'EmailTransport' => [
'SendGridEmail' => [
'className' => 'SendGridEmail.SendGrid',
'api_key' => 'API_KEY'
],
and the delivery profile
'Email' => [
'SendGrid' => [
'transport' => 'SendGridEmail',
'template' => 'default',
'layout' => 'default',
'emailFormat' => 'both',
'from' => ['coms#me.co' => 'Me'],
'sender' => ['coms#me.co' => 'Me'],
]
]
I'd really appreciate if someone can point me out any mistake or a possible solution for my problem.
Hi there this might be too late but in case if anyone facing the same issue.
This is working for me
So the first mistake you did is you are using the Email class, with sendgrid you should be using sendgrid Mail method now
I assume you have already installed this package if not go ahead and add it to the composer.json file and update composer
"sendgrid/sendgrid": "~7",
After that you can use sendgrid class for sending emails like shown in example below
protected function sendEmail($to, $subject, $content)
{
$email = new \SendGrid\Mail\Mail();
$email->setFrom(Configure::consume('App.from_email'), Configure::consume('Theme.title'));
$email->setSubject($subject);
$email->addTo($to);
$email->addContent("text/html", 'Your email body');
$sendgrid = new \SendGrid(Configure::consume('App.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";
}
}
You need to replace sendgrid_api_key with your api key. I am using it from my configuration file.

AWS SES on PHP error: Unable to determine service/operation name to be authorized

I am trying to send email using AWS SES using the following PHP script:
<?php
require_once("phar://aws.phar");
use Aws\Ses\SesClient;
//Open client
$client = SesClient::factory(array(
"key" => "key",
"secret" => "secret",
"region" => "region"
));
$subject = "subject";
$messageText = "text message";
$messageHtml = "<h1>formatted message</h1>";
//Send email
try{
$response = $client->sendEmail(
array(
'Source' => 'verified_email#domain.com',
'Destination' => array(
'ToAddresses' => array('an_address#domain.com')
),
'Message' => array(
'Subject' => array('Data' => $subject),
'Body' => array('Text' => array('Data' => $messageText)),
'Html' => array('Data' => $messageHtml)
)
)
);
}catch(Exception $e){
//An error happened and the email did not get sent
echo($e->getMessage());
}
?>
Whenever I run this, it goes to the catch clause and prints to the screen the message:
Unable to determine service/operation name to be authorized
This doesn't really give me any information on what's wrong and there's no documentation on the API page about this. Any ideas?

Laravel: How to Queue mails to send later

Im trying to use the Mail::queue to send and email, but when I call this function it simple sends the mail, and the response is delayed ... I thought that the point of using Mail::queue was to queue ....
I want the response to came instantly, not having to wait for the email to be sent
for eg
Mail::queue('emails.template', $data, function($message) {
$message->to('somemail#gmail.com');
$message->subject('Notificacion');
});
return Response::json(array('error' => 0, 'message' => 'Ok'));
I want to receive the response without waiting for the mail to be sent.
How can I do that???
What queue driver (app/config/queue.php - 'default' param) are you using? If you're using sync, and haven't set up one of the others, then you're using the synchronous driver, which does exactly what the name says: Runs your queued task as soon as the task is created.
You need to configure an MQ server for Laravel to talk to. You can get a free iron.io account for this, and then you need to configure it, for instance:
'iron' => array(
'driver' => 'iron',
'project' => 'iron-io-project-id',
'token' => 'iron-io-queue-token',
'queue' => 'queue-name',
),
Then when you use Mail::queue() it will push the instruction to iron.io. You'll then have to have another thread listening on the queue - just run php artisan queue:listen and leave it running while messages are pushed to the queue.
/**
* Get all email recipients and include their user details for Mailgun's
* template tags - %recipient.userToken%
*/
private function getRecipients()
{
foreach (User::get() as $user)
{
$this->recipients[$user->email] = [
'id' => $user->id,
'userToken' => $user->user_token,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'email' => $user->email
];
}
}
private function sendEmail()
{
$subject = 'Demo Subject';
/**
* Data for the Blade template
*/
$data = [
'foo' => 'bar'
];
// Inline the CSS for the email
$inliner = new InlineEmail('emails.some-email', $data);
$content = $inliner->convert();
// Create Emails table entry for this email. Used for Mailgun webhooks
$email = Email::create(['user_id' => $this->userId, 'subject' => $subject, 'email_id' => str_random()]);
// Prepare the email addresses
$emailAddresses = array_column($this->recipients, 'email');
$this->mailgun->sendMessage('demo.org', [
"from" => 'support#demo.org',
"to" => implode(',', $emailAddresses), // Comma separated list of email addresses
"subject" => $subject,
"html" => $content, // Inlined CSS HTML from Blade
"text" => "Plain text message here",
"recipient-variables" => json_encode($this->recipients), // Required for batch sending, matches to recipient details
"v:messageId" => $email->id, // Custom variable used for webhooks
]);
}

Categories