咱们采用 'nette/mail' 包做为咱们的邮件发送基础模块,在它的基础上封装一个 'Mail' 类,暴露出简洁的 API 给控制器使用,下面咱们正式开始。php
引入 'nette/mail' 包,修改 'composer.json':git
"require": { "codingbean/macaw": "dev-master", "illuminate/database": "*", "filp/whoops": "*", "nette/mail": "*" }
运行 'composer update',等待安装完成。'nette/mail' 的文档位于:http://doc.nette.org/en/2.2/mailing 让咱们阅读它,而后设计 Mail 类:github
新建 'services/Mail.php' 文件,内容以下:json
<?php use Nette\Mail\Message; date_default_timezone_set('PRC'); /** * Mail */ class Mail { public $config; // [String] e-mail protected $from; // [Array] e-mail list protected $to; protected $title; protected $body; protected $mail; /** * Mail constructor. * @param $to */ function __construct($values) { $this->mail = new Message; $this->config = require_once BASE_PATH . '/config/mail.php'; $this->mail->setFrom($this->config['username']); if ( !is_array($values) ) { $values = [$values]; } foreach ($values as $email) { $this->mail->addTo($email); } } /** * 发件人 * @param null $from * @return $this */ public function from($from=null) { if ( !$from ) { throw new InvalidArgumentException("邮件发送地址不能为空!"); } $this->mail->setFrom($from); return $this; } /** * 收件人 * @param null $to * @return Mail */ public static function to($values=null) { if ( !$values ) { throw new InvalidArgumentException("邮件接收地址不能为空!"); } return new Mail($values); } /** * 邮件标题 * @param null $title * @return $this */ public function title($title=null) { if ( !$title ) { throw new InvalidArgumentException("邮件标题不能为空!"); } $this->mail->setSubject($title); return $this; } /** * 邮件内容 * @param null $content * @return $this */ public function content($content=null) { if ( !$content ) { throw new InvalidArgumentException("邮件内容不能为空!"); } $this->mail->setHTMLBody($content); return $this; } function __destruct() { $mailer = new Nette\Mail\SmtpMailer($this->config); $mailer->send($this->mail); } }
Mail 类和 View 类工做的方式基本一致,在homecontroller.php中添加:数组
function mail() { Mail::to(['xxxxx@qq.com']) ->from('Evai <xxx@163.com>') ->title('Hello World') ->content('<h1>Hello World !</h1>'); echo '发送邮件成功'; }
新建 'MFFC/config/mail.php',请自行替换邮件地址和密码:composer
<?php return [ 'host' => 'smtp.163.com', 'username' => 'Evai <xxx@163.com>', 'password' => 'password', 'secure' => '', 'context' => [ 'ssl' => [ ], ], ];
routs.php中添加一条路由:
Route::get('mail', 'HomeController@mail');
OK,准备的差很少了,运行 'composer dump-autoload' 把 Mail 类加入自动加载,刷新页面!异步
若是你看到以上页面,恭喜你!邮件发送成功了!函数
赶快去检查一下收件箱有木有邮件!此次页面加载可能会稍慢,由于邮件是同步发送的。异步的队列系统咱们会在之后讲到。oop
邮件发送的总体流程想必你们已经轻车熟路了,如今主要叙述一下 Mail 类的设计过程:ui