配置CakePhp以使用SMTP发送邮件

时间:2019-10-28 08:28:37

标签: php cakephp cakephp-3.0

出于安全目的,我的Web服务器已禁用邮件,现在我需要重新配置cakephp代码以按照主机的建议通过SMTP发送电子邮件。

我的代码在启用了php邮件的本地主机上运行良好

use Cake\Mailer\Email;

class LoansController extends AppController

public function sendtestemail(){
$email = new Email();
$email->setViewVars(['name' => 'test test', 'subject'=>'subject test', 
'message'=>'testit']);
$email
->template('bulkemail')
->emailFormat('html')
->to('info@test.co.ke')
->from('info@test.co.ke')
->subject($subject)
->send();
}

错误: 无法发送电子邮件:出于安全原因,已禁用mail() Cake \ Network \ Exception \ SocketException

2 个答案:

答案 0 :(得分:1)

  

我的代码在启用了php邮件的本地主机上运行良好

它可以在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

答案 1 :(得分:0)

对我有用的是来自https://book.cakephp.org/2/en/core-utility-libraries/email.html

编辑/app/Config/email.php

public $smtp = array(
       'transport' => 'Smtp',
        'from' => array('xxxxxxxxxx@gmail.com' => 'Betting site'),
        'host'      => 'ssl://smtp.gmail.com',
        'port'      => 465,
        'username'  => 'xxxxxxxxxx@gmail.com',
        'password'  => 'xxxxxxxxxxpass',
        'client'    => null,
        'log'       => true
        );