文档
安装
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();
$mail->Host = config('mail.MAIL_HOST');
$mail->Port = config('mail.MAIL_PORT');
$mail->SMTPAuth = true;
$mail->Username = config('mail.MAIL_USERNAME');
$mail->Password = config('mail.MAIL_PASSWORD');
$mail->SMTPSecure = 'ssl';
$mail->setFrom(config('mail.MAIL_USERNAME'), config('mail.MAIL_FROM_NAME'));
foreach ($address_list as $address) {
$mail->addAddress($address);
}
$mail->isHTML(true);
$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
{
public function testSend()
{
MailService::send('标题', '内容', ['xxx@qq.com']);
}
}
如果需要发送内容更丰富的html,可以引入模板引擎去渲染邮件内容 PHP:ThinkPHP使用Twig渲染html
参考 PHP 使用 phpmailer 发送电子邮件
|