Как использовать контроллер для отправки почты на новое событие - Cakephp - PullRequest
0 голосов
/ 30 июня 2018

Я выполняю задание Cron в Windows для отправки почты, используя PHPMailer библиотека

cd / d c: \ wamp64 \ www \ project \ bin почта пользователей торта

Редактировать:

Как вызвать функцию с другого контроллера?

UsersController

  private function sendResetEmail($url, $user) 

Вызовите его внутри функции добавления EventsController

Я хотел бы, чтобы каждый подключенный пользователь получал электронную почту, связанную с

пример:

$this->set('user_session', $this->request->session()->read('Auth.User'));

И затем, если этот пользователь создал новое событие, отправьте электронное письмо этому пользователю. а затем пообедаем в Cron другими словами, мне нужно отправить письмо из функции добавления внутри моего EventController

Но сначала я должен вызвать его из моей индексной функции

, изменив это

EventsController.php

<?php
namespace App\Controller;

use App\Controller\AppController;
use Cake\Console\ShellDispatcher;
use Cake\Routing\Router;
use Cake\Event\Event;

class EventsController extends AppController
{
public $components = array("Email");

public function index()
{
        //$to = $user_session['email'];
        $to = 'exemple@gmail.com';
    $subject = 'Hi buddy, i got a message for you.';
    $message = 'Nothing much. Just test out my Email Component using PHPMailer.';

    try {
        $mail = $this->Email->send_mail($to, $subject, $message);
        print_r($mail);
    } catch (Exception $e) {
        echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
    }
    exit;   

}
public function run($username = null){
    $shell = new ShellDispatcher();
    $output = $shell->run(['cake', 'users', $username]);
    debug($output);

    if ($output === 0){
        echo "Shell Command execute";
    }else{
        echo "Fail Command execute";
    }
    exit;
}
    public function add()
{
    $event = $this->Events->newEntity();
    if ($this->request->is('post')) {
        $event = $this->Events->patchEntity($event, $this->request->data);
        if ($this->Events->save($event)) {
            //function send_mail to user who crated Event
            $this->Flash->success(__('The event has been saved.'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('The event could not be saved. Please, try again.'));
        }
    }
    $this->set('eventTypes', $this->Events->EventTypes->find('list'));
    $this->set(compact('event'));
    $this->set('_serialize', ['event']);
    $this->set('user_session', $this->request->session()->read('Auth.User'));
    $this->viewBuilder()->setLayout('user');
}
}

UsersShell.php

 <?php
namespace App\Shell;

use Cake\Console\Shell;
use Cake\Log\Log;
use Cake\Controller\Component;
use Cake\Controller\ComponentRegistry;
use App\Controller\Component\EmailComponent;

class UsersShell extends Shell
{
public function initialize()
{
    parent::initialize();
    $this->loadModel('Users');
    //Load Component 
    $this->Email = new EmailComponent(new ComponentRegistry());
}
public function main()
{
    if (empty($this->args[0])) {

        Log::write('debug', "Please enter a username.");
        return $this->abort('Please enter a username.');
        return false;
    }
    $user = $this->Users->findByUsername($this->args[0])->first();
    if ($user)
    {
        Log::write('debug', "Welcome to ". $user->username);
        $this->out("Welcome to ". $user->username);
        return true;

    } else
    {
        Log::write('debug', 'User cannot be found');
        $this->abort('User cannot be found', 128);
        return false;
    }
}
public function mail()
{
    if (empty($this->args[0])) {
        return $this->abort('Please enter a email address.');
     }

    $to = $this->args[0];
    $subject = 'Hi buddy, i got a message for you.';
    $message = 'Just test out my Email Component using PHPMailer.';

    $mail = $this->Email->send_mail($to, $subject, $message);
    if ($mail) {
        $this->out("Mail Successfully Sent For :: ". $to);
    } else {
        $this->out("Mail Error.");
    }
}
}

EmailComponent.php

<?php
namespace App\Controller\Component;

use Cake\Controller\Component;
use Cake\Core\App;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require ROOT. '/vendor/phpmailer/phpmailer/src/Exception.php';
require ROOT. '/vendor/phpmailer/phpmailer/src/PHPMailer.php';
require ROOT. '/vendor/phpmailer/phpmailer/src/SMTP.php';

class EmailComponent extends Component {

public function send_mail($to, $subject, $message)
{
    $sender = "xxx@gmail.com"; // this will be overwritten by GMail

    $header = "X-Mailer: PHP/".phpversion() . "Return-Path: $sender";

    $mail = new PHPMailer();

    $mail->SMTPDebug  = 2; // turn it off in production
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com'; 
    $mail->SMTPAuth = true;
    $mail->Username   = "exemple@gmail.com";  
    $mail->Password   = "xxxxxx";
    $mail->SMTPSecure = "tls"; // ssl and tls
    $mail->Port = 587; // 465 and 587

    $mail->SMTPOptions = array (
        'tls' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        ),
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )
    );

    $mail->From = $sender;
    $mail->FromName = "From Me";

    $mail->AddAddress($to);

    $mail->isHTML(true);
    $mail->CreateHeader($header);

    $mail->Subject = $subject;
    $mail->Body    = nl2br($message);
    $mail->AltBody = nl2br($message);

    // return an array with two keys: error & message
    if(!$mail->Send()) {
        return array('error' => true, 'message' => 'Mailer Error: ' . $mail->ErrorInfo);
    } else {
        return array('error' => false, 'message' =>  "Message sent!");
    }
}

}

Редактировать: я добавляю мою пересылку, которая может помочь

UsersController

 private function sendResetEmail($url, $user) {
    $email = new Email();
    $email->template('resetpw');
    $email->emailFormat('both');
    $email->from('no-reply@naidim.org');
    $email->to($user->email, $user->full_name);
    $email->subject('Reset your password');
    $email->viewVars(['url' => $url, 'username' => $user->username]);
    if ($email->send()) {
        $this->Flash->success(__('Check your email for your reset password link'));
    } else {
        $this->Flash->error(__('Error sending email: ') . $email->smtpError);
    }
 }

 public function reset($passkey = null) {
    if ($passkey) {
        $query = $this->Users->find('all', ['conditions' => ['passkey' => $passkey, 'timeout >' => time()]]);
        $user = $query->first();

        if ($user) {
            if (!empty($this->request->data)) {

                // Clear passkey and timeout
                $this->request->data['passkey'] = null;
                $this->request->data['timeout'] = null;
                //$user = $this->Users->patchEntity($user, $this->request->data);
          $user->password = $this->request->data['password'];

                if ($this->Users->save($user)) {
                    $this->Flash->success('Password has been Updated.');
                    return $this->redirect(array('action' => 'login'));
                } else {
                 $this->Flash->success('Password Could not be updated');
                }
            }
        } else {
            $this->Flash->error('Invalid or expired passkey. Please check your email or try again');
            $this->redirect(['action' => 'password']);
        }
        unset($user->password);
        $this->set(compact('user'));
    } else {
        $this->redirect('/');
    }
}

Так что я спрашиваю, как отправить почту внутри функции добавления?

Редактировать: как это называется на мой взгляд?

index.ctp

 <li role="presentation" class="dropdown">
              <a href="javascript:;" class="dropdown-toggle info-number" 
    data-toggle="dropdown" aria-expanded="false">
                <i class="fa fa-envelope-o"></i>
                <span class="badge bg-green">6</span>
              </a>
              <ul id="menu1" class="dropdown-menu list-unstyled msg_list" role="menu">
                <li>
                  <a>r
                    <span class="image"><?php echo $this->Html->image($user_session['photo']); ?></span>
                    <span>
                      <span>Zak</span>
                      <span class="time">3 mins ago</span>
                    </span>
                    <span class="message">
                      Film festivals used to be do-or-die moments for movie makers. They were where...
                    </span>
                  </a>
                </li>

1 Ответ

0 голосов
/ 30 июня 2018

Сначала создайте UserListener.php файл в src\Event\UserListener.php Путь. Как это

<?php
namespace App\Event;

use Cake\Event\EventListenerInterface;
use Cake\Log\Log; 

class UserListener implements EventListenerInterface
{
    public function implementedEvents()
    {
        return [
            'Model.Users.afterRemove' => 'afterRemove',
        ];
    }

    public function afterRemove($event, $user)
    {
        Log::write('debug', $user. ' has deleted his/her account.');
    }
}

Теперь используйте afterRemove Событие в контроллере

<?php
namespace App\Controller;

use App\Controller\AppController;
use Cake\Event\Event;
use App\Event\UserListener; // Load Event Class
use Cake\Event\EventManager;

class PagesController extends AppController
{
    public function index()
    {
        $UserListener = new UserListener();
        EventManager::instance()->on($UserListener); 

        $event = new Event('Model.Users.afterRemove', $this, ['user' => 1]);
        $this->getEventManager()->dispatch($event);

        exit;
    }
}

журналы \ debug.log

2018-06-30 04:41:11 Debug: 1 has deleted his/her account.
2018-06-30 04:41:16 Debug: 1 has deleted his/her account.
...