ThinkPHP5.*使用PHPMailer发送邮件的使用及发送失败解决办法

本文详细介绍了如何使用PHPMailer库发送带有附件的电子邮件,包括安装、配置和代码示例。特别强调了SMTP服务器的正确配置及授权码的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.安装:composer require phpmailer/phpmailer

2.引入:use PHPMailer\PHPMailer\PHPMailer;(composer安装不需要引入)

3.调用:$mail = new PHPMailer ();

写一个方法调用发送文件接口

/**
 * 系统邮件发送函数
 * @param string $tomail 接收邮件者邮箱
 * @param string $name 接收邮件者名称
 * @param string $subject 邮件主题
 * @param string $body 邮件内容
 * @param string $attachment 附件列表
 * @return boolean
 * @author static7 <static7@qq.com>
 */
function send_mail($tomail, $name, $subject = '', $body = '', $attachment = null) {
     $mail = new PHPMailer;          //实例化PHPMailer对象
    $mail->CharSet = 'UTF-8';           //设定邮件编码,默认ISO-8859-1,如果发中文此项必须设置,否则乱码
    $mail->IsSMTP();                    // 设定使用SMTP服务
    $mail->SMTPDebug =0;               // SMTP调试功能 0=关闭 1 = 错误和消息 2 = 消息
    $mail->SMTPAuth = true;             // 启用 SMTP 验证功能
    $mail->SMTPSecure = 'ssl';          // 使用安全协议
    $mail->Host = "smtp.163.com"; // SMTP 服务器
    $mail->Port = 465;                  // SMTP服务器的端口号
    $mail->Username = "xxx@163.com";    // SMTP服务器用户名
    $mail->Password = "xxxx";     // SMTP服务器密码 这里是授权码不是邮箱密码真的很坑
    $mail->SetFrom('xxx@163.com', '小明');
    $replyEmail = '小明';                   //留空则为发件人EMAIL
    $replyName = '';                    //回复名称(留空则为发件人名称)
    $mail->AddReplyTo($replyEmail, $replyName);
    $mail->Subject = $subject;
    $mail->MsgHTML($body);
    $mail->AddAddress($tomail, $name);
    if (is_array($attachment)) { // 添加附件
        foreach ($attachment as $file) {
            is_file($file) && $mail->AddAttachment($file);
        }
    }
    return $mail->Send() ? true : $mail->ErrorInfo;
}

测试的时候可能会出现两个问题,导致发送失败,显示"SMTP connect() failed",请按如下不走检查

1.首先检查php是否安装openssl模块

找到php.ini文件并打开,将extension=php_openssl.dll这个句代码前的“;”去掉就OK了

2.就是$mail->Password = "xxxx";   这里是授权码不是邮箱密码请务必注意,我就是失败在这里  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值