使用 composer 构建 PHP 框架之引入发送邮件类库 (七)

1,149 阅读1分钟
原文链接: www.36nu.com

选择 nette/mail  作为发送邮件库

修改composer.json增加一个 require 项:

"nette/mail": "*"

运行composer update完成安装,新建config/email.php

return array(

    'host' => '',//例如 smtp.qq.com

    'username' => '',//用户名

    'password' => '',//密码

    'secure' => 'ssl'
);

修改 assists/factory.php,增加一个方法:

public static function mail(){

    return new \Nette\Mail\SmtpMailer(require BASE_PATH.'/config/mail.php');

}

新建assists/mail.php

config = require BASE_PATH.'/config/mail.php';

        $this->setFrom($this->config['username']);

        if ( is_array($to) ) {

            foreach ($to as $email) {

                $this->addTo($email);

            }

        } else {

            $this->addTo($to);

        }

    }

    public function from($from=null){

        if ( !$from ) {

            throw new InvalidArgumentException("send email address required!");

        }

        $this->setFrom($from);

        return $this;

    }

    public static function to($to=null){

        if ( !$to ) {

            throw new InvalidArgumentException("receive email address required!");

        }

        return new self($to);

    }

    public function title($title=null){

        if ( !$title ) {

            throw new InvalidArgumentException("email title required!");

        }

        $this->setSubject($title);

        return $this;

    }

    public function content($content=null){

        if ( !$content ) {

            throw new InvalidArgumentException("email content required!");

        }

        $this->setHTMLBody($content);

        return $this;

    }
}

然后运行 composer dump-autoload,修改controllers/HomeController.php为:

content('test')->title('test');

        Factory::mail()->send($mail);
    }
}

访问nuf.dev/index.php/home即可发送邮件