我的代码在启用 php 邮件的 localhost 上运行良好
它在 localhost 中可以正常工作,但在您的远程托管中却不行,因为您的托管公司禁用了它,而您可能对它没有太多控制权。
要在 cakephp 中发送电子邮件,请使用 Cakephp 的 Email 类 3. 在 config 文件夹下的 app.php 中,在表 EmailTransport 中添加一个新条目。
在您的情况下是“Smtp”。在其中指定主机、端口、用户名和密码:
'EmailTransport' => [
'default' => [
'className' => 'Smtp',
// The following keys are used in SMTP transports
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => 'user',
'password' => 'secret',
'client' => null,
'tls' => null,
'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
],
‘mail’=> [
'host' => 'smtp.gmail.com',
'port' => 587,
'username' =>xxxxx', //gmail id
'password' =>xxxxx, //gmail password
'tls' => true,
'className' => 'Smtp'
]
],
现在在Controller中,发送电子邮件的功能使用上面写的transport()函数中的条目,如下所示。
在控制器中添加路径-使用 Cake\Mailer\Email:
function sendEmail()
{
$message = "Hello User";
$email = new Email();
$email->transport('mail');
$email->from(['Sender_Email_id' => 'Sender Name'])
->to('Receiver_Email_id')
->subject(‘Test Subject’)
->attachments($path) //Path of attachment file
->send($message);
}
还要记住,许多托管公司也阻止默认 smtp 端口。 (例如,我知道数字海洋就是这样做的)。因此,您可能需要更改该端口或联系他们为您打开它(通常在某种验证之后)。
关于我刚才回答的一些参考:https://www.digitalocean.com/community/questions/digital-ocean-firewall-blocking-sending-email