tp5发送email功能: PHPmailer

时间:2022-09-24 17:22:01

第一步:使用composer安装phpmailer

  1. composer require phpmailer/phpmailer

第二步:common.php写个发送邮件的函数

/**
 * 系统邮件发送函数
 * @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 \phpmailar\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 = "";     // SMTP服务器密码
    $mail->SetFrom('xxx@163.com', 'xxx');
    $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;
}

注意以上代码,由于composer安装的PHPmailer类在phpmailer包中因此实例化时正确路由是  new \phpmailer\PHPmailer()

第三步:控制器方法里写发送的内容

public function email() {
        $toemail='static7@qq.com';
        $name='static7';
        $subject='QQ邮件发送测试';
        $content='恭喜你,邮件测试成功。';
        send_mail($toemail,$name,$subject,$content);
    }

第四步:测试发送

博客链接:https://www.calm7.com/article/5.html