通过cakePHP发送邮件

时间:2013-11-12 15:40:31

标签: cakephp cakephp-2.3

我使用以下代码段发送邮件,但转移到其他主机时搞砸了所有内容:

    public function forgetpwd(){    
//code omitted
    if($this->User->saveField('token_hash',$fu['User']['token_hash'] )){

                            //============Email================//
                            /* SMTP Options */
                            $this->Email->smtpOptions = array(
                                    'host' => 'smtp.gmail.com',                             
                                    'port'=>'465',
                                    'transport' => 'Smtp',
                                    'username'=>'email@gmail.com',
                                    'password'=>'secret',
                                    'tls' => true
                            );
                            $this->Email->template = 'resetpw';
                            $this->Email->from    = 'noreply@email.com';
                            $this->Email->to      = $fu['User']['name'].'<'.$fu['User']['email'].'>';
                            $this->Email->subject = __('Recover your password');
                            $this->Email->sendAs = 'both';

                            $this->Email->delivery = 'smtp';
                            $this->set('ms', $ms);
                            $this->Email->send();
                            $this->set('smtp_errors', $this->Email->smtpError);
                            $this->Session->setFlash(__('Check your email to recover your password'));
}

                            //============EndEmail=============//

所以有这个视图 forgetpwd.ctp ,要求用户输入他/她的电子邮件地址,在尝试发送电子邮件时,我会收到以下两个错误:

Error: The view for UsersController::forgetpwd() was not found.

Error: Confirm you have created the file: /home/public_html/development/app/View/Emails/text/resetpw.ctp

我确信 resetpw.ctp 存在于正确的位置。

我已经编辑了电子邮件配置并试图采用2.3 cakePHP方式,这就是我最终得到的结果:

            if($this->User->saveField('token_hash',$fu['User']['token_hash'] )){

                App::uses('CakeEmail', 'Network/Email');

                $Email = new CakeEmail('default');

                $Email->to($fu['User']['email'])
                        ->subject('Reset your password')
                        ->message($key)
                        ->send();

                $this->Session->setFlash(__('Check your mail to reset your password'));

                $this->redirect(array('controller'=>'users','action'=>'reset'));

但是现在,当我尝试发送电子邮件时,我收到以下错误:

Call to a member function send() on a non-object

1 个答案:

答案 0 :(得分:0)

更改

'host' => 'smtp.gmail.com',                             

'host' => 'ssl://smtp.gmail.com',

还将您的配置信息放在app / Config /中的email.php中,如下所示:

http://book.cakephp.org/2.0/en/core-utility-libraries/email.html#configuration