- PHPMailer 需要 PHP 的 sockets 扩展支持,而登录 QQ 邮箱 SMTP 服务器则必须通过 SSL 加密,故 PHP 还得包含 openssl 的支持。
- PHPMailer 核心文件:
- PHP扩展确认开启之后,需要开启QQ邮箱的SMTP 服务
1). 打开qq邮箱->设置->账户
2). 滑到页面底部,找到SMTP服务并开启
3). 发送短信验证:
4). 发送完成后点击我已发送,获取授权码:
- 代码实例:
注意,下面use的依赖包为必要条件,如果项目中没有包,自己composer引入,如:composer require nette/mail
<?phpnamespace Controllers\Api;use Slim\Http\Request;
use Slim\Http\Response;
use Nette\Mail\Message;
use Nette\Mail\SendmailMailer;
use Nette\Mail\SmtpMailer;class UserController{// SMTP服务器private $server;// SMTP服务器的端口private $port;// SMTP服务器的用户邮箱private $email;//SMTP服务器的用户帐号private $username;//SMTP服务器的用户密码private $password;// 发件人姓名private $name = '';public function __construct($config = []) {$this->server = 'smtp.qq.com';$this->port = '465';$this->email = 'xxx@qq.com';$this->username = 'xxx@qq.com';$this->password = '授权码';$this->name = '月月';}/*** send: 发送邮件* @param string $accept 接收人* @param string $title 邮件标题* @param string $content 邮件内容* @return bool 发送成功返回true*/public function send($accept, $title, $content) {$mail = new Message();try {$mail->setFrom($this->name . ' <' . $this->email . '>')->addTo($accept)->setSubject($title)->setBody($content);$mailer = new SmtpMailer(['host' => $this->server,'username' => $this->username,'password' => $this->password,]);$mailer->send($mail);return true;} catch (AssertionException $e) {return false;}}public function register(Request $request, Response $response, $args){$email = $request->getParam('email');$this->send('xxx@qq.com', '测试邮件', 'hello world');}
}