Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
803 views
in Technique[技术] by (71.8m points)

cakephp - how can i set email by a variable in cakehphp app_local

In app_local how can i set username and password with variables in cakephp 4 ? I want to get the values from a table. Or if i cant use a variable to set the email then is there another way?

 'EmailTransport' => [
            'default' => [
                'host' => 'ssl://smtp.gmail.com',
                'port' => 465,
                'username'=>'[email protected]',
                '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',
                'port' => 465,
                'username'=>$username,
                'password'=>$password,

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

question from:https://stackoverflow.com/questions/65844833/how-can-i-set-email-by-a-variable-in-cakehphp-app-local

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Keep the default email settings in your configuration file.

In your controller actions do something like this:

use CakeMailerMailerAwareTrait;
use CakeMailerTransportFactory;
// ....
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]);
    }
}

or try this:

$this->getMailer('Users')
->drop('gmail')
->setConfig('gmail', [
    'host' => 'ssl://smtp.gmail.com',
    'port' => 465,
    'username' => $user->mail_username,
    'password' => $user->mail_password,
    'className' => 'Smtp',
 ])
->send('user', [$user]);

read more https://book.cakephp.org/4/en/core-libraries/email.html#configuring-transports

note: for security reasons, be sure not to save a plain text password to the database


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...