我正在Windows上执行Cron作业以使用以下方式发送邮件 PHPMailer库
cd / d c:\ wamp64 \ www \ project \ bin 蛋糕用户邮件
编辑:
How to call function from another controller ?
UsersController
private function sendResetEmail($url, $user)
在EventsController添加函数中调用
我想为每个已连接的用户检索与
相关的电子邮件示例:
$this->set('user_session', $this->request->session()->read('Auth.User'));
然后,如果该用户创建了新事件,则将电子邮件发送给该用户。 然后午餐克朗工作 换句话说,我需要从EventController内部的add函数发送邮件
但是首先我必须从索引函数中调用它
通过更改
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('/');
}
}
那我问如何在add函数中发送邮件?
编辑:如何在我的视图中调用它?
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>
答案 0 :(得分:1)
首先在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;
}
}
logs \ 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.