I have written generating email functionality inside public function add().
My idea is to send my to the users who had registered.
my add functionality looks like this.
add functionality is working fine but mail generation giving error says Unknown email configuration "gmail". Any help please.
app/Controller/UsersController.php
<?php
App::uses('AppController', 'Controller');
class UsersController extends AppController {
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$data[] = $this->request->data;
foreach($data as $row){
$email_name = $row['User']['username'];
$password = $row['User']['password'];
}
$data = array();
$subject = "Visualization Tool Login credentials";
// From
$header="manasasirsi17#gmail.com";
// Your message
$message="welcome user\r\n";
$message.="Thank You for Registering\r\n";
$message.="your login details are as given below\r\n";
$message.="username:$email_name\r\n";
$message.="password:$password\r\n";
App::uses('CakeEmail', 'Network/Email');
$smtp = new CakeEmail('smtp');
$smtp->from(array($header => $header));
$smtp->to($email_name);
$smtp->subject($subject);
$smtp->emailFormat('html');
$Email->send($message);
$this->Session->setFlash(__('Login Details are sent to You via Email.'));
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('controller' => 'Users', 'action' => 'login'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
}
app/Config/email.php
class EmailConfig {
public $default = array(
'transport' => 'Mail',
'from' => 'you#localhost',
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
public $smtp = array(
'transport' => 'Smtp',
'host' => 'ssl://smtp.gmail.com',
'port' => 25,
'timeout' => 30,
'username' => 'manasasirsi17#gmail.com',
'password' => 'secure',
'client' => null,
'log' => false
);
public $fast = array(
'from' => 'you#localhost',
'sender' => null,
'to' => null,
'cc' => null,
'bcc' => null,
'replyTo' => null,
'readReceipt' => null,
'returnPath' => null,
'messageId' => true,
'subject' => null,
'message' => null,
'headers' => null,
'viewRender' => null,
'template' => false,
'layout' => false,
'viewVars' => null,
'attachments' => null,
'emailFormat' => null,
'transport' => 'Smtp',
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => 'user',
'password' => 'secret',
'client' => null,
'log' => true,
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
}
You've not defined a gmail email config in your EmailConfig class. This line:-
$Email = new CakeEmail('gmail');
should be from the looks of your code:-
$Email = new CakeEmail('smtp');
The parameter you pass to CakeEmail determines which of the defined configs in EmailConfig you want to use. If you had wanted to pass it gmail you would have needed to add a $gmail property to the EmailConfig class containing the configuration.
Related
I'm trying to trigger push notifications and emails in the background of my Lumen API. I created the WarningUser class that creates both queues:
<?php
namespace App\Utils;
use App\Jobs\ProcessNotification;
use App\Mail\AllMail;
use Illuminate\Support\Facades\Mail;
class WarningUser
{
public static function send($user, $message, $url, $data = [])
{
$url = env('APP_URL_FRONT') . $url;
dispatch(new ProcessNotification($user, $data, $message, $url));
$emailData = EmailTexts::texts('pt', $data)[$message];
Mail::to($user->email)->queue(new AllMail($emailData['title'], $emailData['content']));
return true;
}
}
First we have the ProcessNotification job, which connects to Firebase and sends the notification:
<?php
namespace App\Jobs;
use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\Notification;
use Kreait\Firebase\Messaging\CloudMessage;
class ProcessNotification extends Job
{
protected $user = null;
protected $data = null;
protected $message = null;
protected $url = null;
public function __construct($user, $data, $message, $url)
{
$this->user = $user;
$this->data = $data;
$this->message = $message;
$this->url = $url;
}
public function handle()
{
if (\is_string($this->user->token) and $this->user->token !== '') {
$messaging = (new Factory())
->withServiceAccount(__DIR__.'/../../private-key.json')
->createMessaging();
$notificationData = NotificationTexts::texts('pt', $this->data)[$this->message];
$messageAlert = CloudMessage::withTarget('token', $this->user->token)
->withNotification(Notification::create($notificationData['title'], $notificationData['content']))
->withData([ 'url' => $this->url ]);
$messaging->send($messageAlert);
}
}
}
And finally AllMail that sends a simple email:
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class AllMail extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
protected $title;
protected $body;
public function __construct($title, $body)
{
$this->title = $title;
$this->body = $body;
}
public function build()
{
return $this
->subject($this->title)
->view('email')
->with([
'title' => $this->title,
'body' => $this->body
]);
}
}
I've tested both codes without using queues, and they work, but when I put the queue it stops working. The processes are recorded in my database (mongodb):
But the queue is never processed, I tried to execute php artisan queue: work andphp artisan queue: listen, but neither case works.
The queue is never attempted to be processed, nor does it go to the failed_jobs table
My config / queue.php is as follows. And my .env is with QUEUE_CONNECTION = database
<?php
return [
'default' => env('QUEUE_CONNECTION', 'database'),
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 90,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => 'localhost',
'queue' => 'default',
'retry_after' => 90,
'block_for' => 0,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'your-queue-name'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => 90,
'block_for' => null,
],
],
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database'),
'database' => env('DB_CONNECTION', 'mongodb'),
'table' => 'failed_jobs',
],
];
Can someone help me? I no longer know what the error may be.
PS: At no time is a browser or console error displayed
I managed to solve, for Mongo we need to use some more settings:
The connection in queue.php must be:
'connections' => [
'database' => [
'driver' => 'mongodb',
'table' => 'jobs',
'queue' => 'default',
'expire' => 60,
],
...
And we need to register the package provider that works with mongo:
Jenssegers\Mongodb\MongodbQueueServiceProvider::class,
I had developed a block in 2.5. I installed the block successfully..and gave permissions settings on front end to view this block only for one role users say 'Manager'. So, Manager/Admin can only view this block and no one else.
But this block is still visible for all. Could you please judge me.. where I went wrong.. Here is my leisure block code
Blocks/block_leisure/block_leisure.php
<?php
class block_leisure extends block_base
{
public function init()
{
global $CFG;
$this->title = get_string('leisure', 'block_leisure');
}
public function get_content()
{
global $COURSE, $DB, $PAGE, $CFG, $USER, $CFG, $SESSION, $OUTPUT;
if ($this->content !== null)
{
return $this->content;
}
$this->content = new stdClass;
$context = $PAGE->context;
$this->content->text = 'This is a leisure block content';
$this->content->footer = 'Footer here...';
return $this->content;
} // Function - get_content().
public function getmodules()
{
return true;
}
}
Blocks/block_leisure/db/access.php
<?php
defined('MOODLE_INTERNAL') || die;
$capabilities = array(
'block/leisure:myaddinstance' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'archetypes' => array(
'user' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/my:manageblocks'
),
'block/leisure:addinstance' => array(
'riskbitmask' => RISK_SPAM | RISK_XSS,
'captype' => 'write',
'contextlevel' => CONTEXT_BLOCK,
'archetypes' => array(
'editingteacher' => CAP_ALLOW,
'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/site:manageblocks'
),
'block/leisure:viewpages' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'manager' => CAP_ALLOW
)
),
'block/leisure:managepages' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'manager' => CAP_ALLOW
)
)
);
and as usual I have lang folder, version.php and read me file.
You need to do something with the capability you have defined, otherwise it will have no effect.
Check the capability within get_content, then return null if nothing should be displayed.
I want to use CakePHP Email to send emails to users with new passwords when a user has forgotten their password. If the user has forgotten their password they will be required to enter their username and corresponding email. The system will check if the username and email match in the database and if so create a random password and send it to the users email account. I'm a beginner and I'm not sure if I'm doing it properly. My code is as follows:
employeesController:
<?php
App::uses('AppController', 'Controller');
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
App::uses('CakeEmail', 'Network/Email');
class EmployeesController extends AppController {
//some code
public function forgotpassword()
{
$username=$this->request->data['fusername'];
//App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
//$passwordHasher = new SimplePasswordHasher();
//$password = $passwordHasher->hash($this->request->data['password']);
$emailaddress=$this->request->data['emailadd'];
$msg = $this->Employee->getUserPassword($username,$emailaddress);
if($msg)
{
foreach ($msg as $userdetails)
{
$userhashedpass=$userdetails['Employee']['employee_pw'];//see access level here
$userid=$userdetails['Employee']['id'];
$useremail=$userdetails['Employee']['employee_email'];
}
$newpassword="$userhashedpass[0]$userhashedpass[4]$userhashedpass[13]$userhashedpass[8]$userhashedpass[11]$userhashedpass[12]";
//send email
$Email = new CakeEmail();
$Email->from(array('anuja_f#hotmail.com' => 'CentreVision CRM'))
->to($useremail)
->subject('New Password')
->send('Your new password is $newpassword ');
/* $to = $useremail;
$subject = "Your New Password";
$txt = "Your new password is $newpassword ";
$headers = "From: admin#centervision.com" . "\r\n";
*/
//send email to the employee
// $reply=$this->Employee->updatenewpassword($username,$emailaddress,$newpassword);
$data = array('id' => $userid, 'employee_pw' => $newpassword);
// This will update Recipe with id 10
$this->Employee->save($data);
//$this->set('msg',$userhashedpass);
//$this->set('newpassword',$newpassword);
$errormsg="Email has been sent to registered email address linked to this username";
//comment out next line to not display the new password on the screen once smtp is configured
$this->set('newpassword',$newpassword);
$this->set('errorfor',$errormsg);
$this->render("../Pages/home");
$this->layout = '../Pages/home';
}
else{
$errormsg="Username and Email does not match";
$this->set('errorfor',$errormsg);
$this->render("../Pages/home");
$this->layout = '../Pages/home';
}
}
//some code
}
And my app/config/email.php:
class EmailConfig {
public $default = array(
'transport' => 'Mail',
'from' => 'anuja_f#hotmail.com',
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
public $smtp = array(
'transport' => 'Smtp',
'from' => array('site#localhost' => 'My Site'),
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => 'user',
'password' => 'secret',
'client' => null,
'log' => false,
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
public $fast = array(
'from' => 'you#localhost',
'sender' => null,
'to' => null,
'cc' => null,
'bcc' => null,
'replyTo' => null,
'readReceipt' => null,
'returnPath' => null,
'messageId' => true,
'subject' => null,
'message' => null,
'headers' => null,
'viewRender' => null,
'template' => false,
'layout' => false,
'viewVars' => null,
'attachments' => null,
'emailFormat' => null,
'transport' => 'Smtp',
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => 'user',
'password' => 'secret',
'client' => null,
'log' => true,
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
}
At the moment when I enter username and email i get the following error:
mail(): Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()
Can someone please help me?
just you need use one configuration:
$Email = new CakeEmail();
$Email->config('default');
or in your case:
$Email = new CakeEmail();
$Email->config('smtp');
or if you want to user a gmail:
$Email = new CakeEmail();
$Email->config('gmail');
and the configuration:
class EmailConfig {
/*public $default = array(
'transport' => 'Mail',
'from' => 'you#localhost',
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
public $smtp = array(
'transport' => 'Smtp',
'from' => array('soyazucar#localhost' => 'Test Site'),
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => 'user',
'password' => 'secret',
'client' => null,
'log' => false,
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);*/
public $gmail = array(
'host' => 'ssl://smtp.gmail.com',
'port' => 465,
'username' => 'guesss#gmail.com',
'password' => 'password',
'transport' => 'Smtp'
);
/*public $fast = array(
'from' => 'contreras.amilkar#gmail.com',
'sender' => null,
'to' => null,
'cc' => null,
'bcc' => null,
'replyTo' => null,
'readReceipt' => null,
'returnPath' => null,
'messageId' => true,
'subject' => null,
'message' => null,
'headers' => null,
'viewRender' => null,
'template' => false,
'layout' => false,
'viewVars' => null,
'attachments' => null,
'emailFormat' => null,
'transport' => 'Smtp',
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => 'user',
'password' => 'secret',
'client' => null,
'log' => true,
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);*/
}
I have some code for send to mail but it's not working properly.
My code is here:
class EmailsController extends AppController
{
var $name="Email";
var $uses = NULL;
public function index()
{
App::import('Component', 'Email');
$path=WWW_ROOT."img";
$filename="Desert.jpg";
$email->from = 'pal#gmail.com';
$email->to='abc#gmail.com';
$email->subject='test mail';
$email->template = 'simple_message';
$email->attachments = array($path.$filename);
$email->SendAs='html';
if($email->send())
{
$this->session->setFlash("Email Send Successfully");
}
else
{
$this->session->setFlash("Email is not send");
}
}
}
I am getting the error like:
Call to undefined method stdClass::send()
Why don't you use var $components? Include Email component the right way:
class EmailsController extends AppController
{
var $name="Email";
var $components = array('Email');
var $uses = NULL;
public function index() {
$path=WWW_ROOT."img";
$filename="Desert.jpg";
$this->Email->from = 'pal#gmail.com';
$this->Email->to='abc#gmail.com';
$this->Email->subject='test mail';
$this->Email->template = 'simple_message';
$this->Email->attachments = array($path.$filename);
$this->Email->sendAs='html';
if($this->Email->send()) {
$this->Session->setFlash("Email Send Successfully");
} else {
$this->Session->setFlash("Email is not send");
}
}
}
For more info please visit: http://book.cakephp.org/2.0/en/core-utility-libraries/email.html
<?php
App::uses('CakeEmail', 'Network/Email');
$email = new CakeEmail( $smtp );
$email->to( 'test#example.com' );
$email->subject(__("Reset Password") );
$email->emailFormat('html');
$email->send($body);
?>
For SMTP:
save this below code with "email.php" file in app/Config folder and put your smtp details in $smtp array. and assign $smtp variable in
new CakeEmail($smtp);
<?php
class EmailConfig {
public $default = array(
'transport' => 'Mail',
'from' => 'you#localhost',
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
public $smtp = array(
'transport' => 'Smtp',
'from' => array('site#localhost' => 'My Site'),
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => 'user',
'password' => 'secret',
'client' => null,
'log' => false,
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
);
}
?>
I'm having problems sending a mail with cakephp2, I know I can send emails because I have my postfix configured, and I can send e-mails with command line or php. So please, can you send me an example of cakephp2 sending emails.
This is the error message
Invalid email: "you#localhost"
Error: An Internal Error Has Occurred.
I've also tried with the ssl via gmail and it doesn't work either, and it's giving me a really hard time.
thanks guys
by the way, I'm trying the exact example of this url http://book.cakephp.org/2.0/en/core-utility-libraries/email.html
Your app/config/Email.
class EmailConfig {
public $gmail = array(
'port' => '465',
'timeout' => '300',
'host' => 'ssl://smtp.gmail.com',
'username' => '<your_email>#gmail.com',
'password' => '<you_password>',
'transport' => 'Smtp'
); }
your file = app/controller/appController.php insert this function
public function sendEmail($type, $options){
try {
$Email = new CakeEmail($type);
$Email->config($options);
$Email->template = "email_confirmation";
$Email->emailFormat('html');
//$this->idCrudRash = $options;
$Email->send();
} catch (SocketException $e) {
die('Erro ao enviar email:'. $e->getMessage());
$this->log(sprintf('Erro ao enviar email: %s', $e->getMessage()));
}
}
for user: app/controller/contato.php
$options = array(
'emailFormat' => 'html',
'from' => array(
$config['email_noanswer'] => $config['site_name']
),
'subject' => 'Confirmação de Cadastro',
'to' => $this->request->data['User']['email'],
//'template' => 'default',
'template' => 'email_confirmation',
'viewVars' => array(
'title_for_layout' => 'Confirmação de Email ' . $config['site_name'],
'name' => $this->request->data['User']['name'],
'email' => $this->request->data['User']['email'],
//'cpf' => base64_encode($this->request->data['User']['cpf']),
'site_name' => $config['site_name'],
),
);
$this->sendEmail('gmail', $options);
In your email.php file, please remove the default 'from' value, it overrides your passed param.
public $default = array(
'transport' => 'Mail',
'from' => 'you#localhost', // remove this line
...
);
In app/config/Email
public $smtp = array(
'transport' => 'Smtp',
'from' => array('no-reply#xyz.com' => 'no-reply#xyz.com'),
'host' => 'ssl://smtp.abc.com',
'port' => 465,
'timeout' => 30,
'username' => 'username',
'password' => 'password',
'client' => null,
'log' => false,
);
In Your Controller
App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');
public function index()
{
$this->layout = 'layout';
$this->set('title', "Title");
if ($this->request->is('Post')) {
if (!empty($this->request->data)) {
if ($this->Modal->Save($this->request->data)) {
$to = 'test#anc.com';
$subject = 'Your_subject';
$message = $this->request->data;
if ($this->sendmail($to, $subject, $message)) {
echo"sent";die;
}
} else {
echo"wrong";die;
}
}
}
}
public function sendmail($to = null, $subject = '', $messages = null, $ccParam = null, $from = null, $reply = null, $path = null, $file_name = null)
{
$this->layout = false;
$this->render(false);
$name = $messages['Modalname']['name'];
$email = $messages['Modalname']['email'];
$Email = new CakeEmail();
$Email->config('smtp');
$Email->viewVars(array('name' => $name, 'email' => $email));
$Email->template('comman_email_template', 'comman_email_template');
return $Email->emailFormat('html')
->from(array('no-reply#xyz.com' => 'no-reply#xyz.com'))
->to($to)
->subject($subject)
->send();
}
Create a layout and view for email template.and add the data value that have been sent.