Effect
The function of sending emails is realized by configuring the module in advance. (This code cannot change the sending email address based on user input information)
Prerequisite
Readers already have basic knowledge of CakePHP
Version
CakePHP 3.6.1
PHP 7.4.10
Preparation
'EmailTransport' => [ 'default' => [ 'className' => 'Smtp', 'host' => 'smtp.gmail.com', 'port' => 587, 'timeout' => 30, 'username' => 'name@gmail.com', 'password' => '12345678', 'tls' => true, 'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null), ], ], 'Email' => [ 'default' => [ 'transport' => 'default', 'from' => 'name@gamail.com', //'charset' => 'utf-8', //'headerCharset' => 'utf-8', ], ],
Go to any Controller.php and write the function for sending emails.
*There is a reference here stackoverflow
//在最上面加载模块 use Cake\Mailer\Email; //在任意class下写邮件发送的函数 public function send() { $email = new Email('default'); try { $email->setFrom(['name@gmail.com' => 'My Site']) ->setTo('接受者邮箱@126.com') ->setSubject('主题') ->send('本文'); echo "success"; } catch (\Cake\Network\Exception\SocketException $exception) { $lastResponse = $email->transport()->getLastResponse(); var_dump($lastResponse); } }
Write the route in
$routes->connect('/send', ['controller' => 'ControllerName', 'action' => 'send']);
error report,This is because the security level of gmail is too high.
Log in to your Google Account Management Center->Security
Turn off two-step verificationEnable access
#Then refresh the page and you will find that we have successfully sent the email through gmail.For account security, remember to increase the security protection level after the test is successful.
Recommended learning: "PHP Video Tutorial"