0

I'm working on CakePHP 3.4

I have a contact_messages table to save message via form on website.

I want to send user an email whenever a new message is saved.

For that, I have created mailer class like

<?php
namespace App\Mailer;

use Cake\Mailer\Mailer;
use Cake\Event\Event;
use Cake\Datasource\EntityInterface;

class ContactMessageMailer extends Mailer
{
    public function newMessage($message)
    {
        $this
            ->setProfile('no-reply')
            ->setTemplate('new_message')
            ->setLayout('message')
            ->setEmailFormat('html')
            ->setTo($user->email)          // user email
            ->setSubject('Verify Account')
            ->setViewVars(['name' => $user->first_name, 'email' => $user->email, 'message' => $message->body]);
    }

    public function implementedEvents()
    {
        return [
            'Model.afterSave' => 'alertMessage'
        ];
    }

    public function alertMessage(Event $event, EntityInterface $entity, \ArrayObject $options)
    {
        if ($entity->isNew()) {
            $this->send('newMessage', [$entity]);
        }
    }
}

and registering event in ContactMessagesTable.php

$mailer = new UserMailer(); //use App\Mailer\UserMailer;
$this->eventManager()->on($mailer);

ContactMessages belongsTo Users and Users is having email of user whom to send the email.

How can I get users information in Mailer?

Anuj TBE
  • 9,198
  • 27
  • 136
  • 285

1 Answers1

0

Will probably do this; In the User table;

public function processUser($user) 
{
  if($this->save($user)){
     $event = new Event('Model.afterSave', $this, [$entity = $user])
     $this->eventManager()->dispatch($event);
     return true;
  }else{
      return false;
   }
}

In ContactMessage Table ;

public function initialize()
{
parent::intialize();
$mailer = new UserMailer(); //use App\Mailer\UserMailer;
$this->Users->eventManager()->on($mailer); //ContactMessage has to be related to User table
}

Hope I was able to communicate.

medhybrid
  • 48
  • 6