文档
- https://github.com/PHPMailer/PHPMailer
安装
composer require phpmailer/phpmailer
代码示例
配置文件 config/mail.php
<?php
// +----------------------------------------------------------------------
// | 邮件系统配置
// +----------------------------------------------------------------------
return [
'MAIL_HOST' => 'smtp.163.com',
'MAIL_PORT' => 465,
'MAIL_USERNAME' => 'xxx@163.com',
'MAIL_PASSWORD' => 'xxxxxx',
'MAIL_FROM_NAME' => '山中无老虎',
];
<?php
namespace app\service;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
class MailService
{
public static function send($subject, $body, array $address_list = [])
{
$mail = new PHPMailer(true);
//服务器配置
$mail->CharSet = "UTF-8"; //设定邮件编码
$mail->SMTPDebug = SMTP::DEBUG_OFF; // 调试模式输出
$mail->isSMTP(); // 使用SMTP
// SMTP服务器
$mail->Host = config('mail.MAIL_HOST');
// 服务器端口 25 或者465 具体要看邮箱服务器支持
$mail->Port = config('mail.MAIL_PORT');
$mail->SMTPAuth = true; // 允许 SMTP 认证
$mail->Username = config('mail.MAIL_USERNAME'); // SMTP 用户名 即邮箱的用户名
$mail->Password = config('mail.MAIL_PASSWORD'); // SMTP 部分邮箱是授权码(例如163邮箱)
$mail->SMTPSecure = 'ssl'; // 允许 TLS 或者ssl协议
//发件人
$mail->setFrom(config('mail.MAIL_USERNAME'), config('mail.MAIL_FROM_NAME'));
// 收件人
foreach ($address_list as $address) {
$mail->addAddress($address);
}
//Content
$mail->isHTML(true); // 是否以HTML文档格式发送 发送后客户端可直接显示对应HTML内容
$mail->Subject = $subject;
$mail->Body = $body;
$mail->send();
}
}
测试
<?php
require_once __DIR__ . '/../../vendor/autoload.php';
((new \think\App())->http)->run();
use app\service\MailService;
use PHPUnit\Framework\TestCase;
class MailServiceTest extends TestCase
{
/**
* @doesNotPerformAssertions
*/
public function testSend()
{
MailService::send('标题', '内容', ['xxx@qq.com']);
}
}
如果需要发送内容更丰富的html,可以引入模板引擎去渲染邮件内容