如何通过 cakehphp app_local 中的变量设置电子邮件

问题描述

在 app_local 中,如何使用 cakePHP 4 中的变量设置用户名和密码?我想从表中获取值。 或者,如果我不能使用变量来设置电子邮件,那么还有其他方法吗?

 'EmailTransport' => [
            'default' => [
                'host' => 'ssl://smtp.gmail.com','port' => 465,'username'=>'xx@gmail.com','password'=>'xx',//how can i do this code below with the variables as i cant get data from a table in this file?     
      
    'EmailTransport' => [
            'default' => [
                'host' => 'ssl://smtp.gmail.com','username'=>$username,'password'=>$password,

https://book.cakephp.org/4/en/core-libraries/email.html

解决方法

在您的配置文件中保留默认电子邮件设置。

在你的控制器动作中做这样的事情:

use Cake\Mailer\MailerAwareTrait;
use Cake\Mailer\TransportFactory;
// ....
public function index()
{
    $users = $this->Users->find();

    foreach ($users as $user) {
        TransportFactory::drop('gmail'); // If you wish to modify an existing configuration,you should drop it,change configuration and then re-add it.
        TransportFactory::setConfig('gmail',[
            'host' => 'ssl://smtp.gmail.com','port' => 465,'username' => $user->mail_username,'password' => $user->mail_password,'className' => 'Smtp',]);

        $this->getMailer('Users')->send('user',[$user]);
    }
}

或者试试这个:

$this->getMailer('Users')
->drop('gmail')
->setConfig('gmail',[
    'host' => 'ssl://smtp.gmail.com',])
->send('user',[$user]);

阅读更多 https://book.cakephp.org/4/en/core-libraries/email.html#configuring-transports

注意:出于安全原因,请确保不要将纯文本密码保存到数据库中

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...