本文以QQ邮箱为案例
1.配置QQ邮箱,获取SMTP 密码



3.开启PHP模块(php.ini)
PHPMailer 需要 PHP 的 sockets 扩展支持,而登录 QQ 邮箱 SMTP 服务器则必须通过 SSL 加密,故 PHP 还得包含 openssl 的支持。

4.composer 安装最新版发送邮件类库
composer require phpmailer/phpmailer:6.1.5
<?php
include './vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//服务器配置
$mail->CharSet ="UTF-8"; //设定邮件编码
$mail->SMTPDebug = 0; // 调试模式输出
$mail->isSMTP(); // 使用SMTP
$mail->Host = 'smtp.qq.com'; // SMTP服务器
$mail->SMTPAuth = true; // 允许 SMTP 认证
$mail->Username = '791816261@qq.com'; // SMTP 用户名 即邮箱的用户名
$mail->Password = 'yfglbjoundvrb***'; // SMTP 密码 部分邮箱是授权码(例如QQ邮箱)
$mail->SMTPSecure = 'ssl'; // 允许 TLS 或者ssl协议
$mail->Port = 465; // 服务器端口 25 或者465 具体要看邮箱服务器支持
$mail->setFrom('791816261@qq.com', 'Mailer'); // 发件人
$mail->addAddress('13691128500@163.com', 'Joe');// 收件人
//$mail->addAddress('ellen@example.com'); // 可添加多个收件人
//$mail->addReplyTo('xxxx@163.com', 'info'); // 回复的时候回复给哪个邮箱 建议和发件人一致
//$mail->addCC('cc@example.com'); // 抄送
//$mail->addBCC('bcc@example.com'); // 密送
//发送附件
// $mail->addAttachment('../xy.zip'); // 添加附件
$mail->addAttachment('./20200429111237.png', 'new.jpg'); // 发送附件并且重命名
//Content
$mail->isHTML(true); // 是否以HTML文档格式发送 发送后客户端可直接显示对应HTML内容
$mail->Subject = '邮件标题';
$mail->Body = '<h1>这里是邮件内容</h1>';
$mail->AltBody = '如果邮件客户端不支持HTML则显示此内容';
$mail->send();
echo '邮件发送成功';
} catch (Exception $e) {
echo '邮件发送失败: ', $mail->ErrorInfo;
}
网友评论