使用PHPMailer实现PHP通过QQ邮箱发邮件功能

第一步

composer require phpmailer/phpmailer

或直接访问https://github.com/PHPMailer/PHPMailer/下载

第二步

检查是否开启socket(PHPMailer 需要 PHP 的 sockets 扩展支持)和openssl(登录 QQ 邮箱 SMTP 服务器则必须通过 SSL 加密)

打开openssl

php.ini中;extension=php_openssl.dll是否存在, 如果存在的话去掉前面的注释符‘;’, 如果不存在这行,那么添加

extension=php_openssl.dll

第三步

QQ邮箱的设置 (其他邮箱未试过,支持 SMTP 协议的应该都可以)

设置->账户->POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务

IMAP/SMTP服务(按操作开启这个,妥善保管SMTP 服务器认证密码,密码没有空格)

第四步

以上流程都完成的情况下,可以使用以下代码(此处使用ThinkPHP5.1)

<?php


use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

class Email
{

    /**
     * 邮件发送
     * @param $to 接收人邮箱地址
     * @param string $subject 邮件标题
     * @param string $content 邮件内容(html模板渲染后的内容)
     * @throws Exception
     * @throws phpmailerException
     */
    function send_email($to,$subject='',$content='')
    {
        $mail = new PHPMailer;
        $mail->CharSet = 'UTF-8'; //设定邮件编码,默认ISO-8859-1,如果发中文此项必须设置,否则乱码
        $mail->isSMTP();
        //Enable SMTP debugging
        // 0 = off (for production use)
        // 1 = client messages
        // 2 = client and server messages
        $mail->SMTPDebug = 0;
        //调试输出格式
        //$mail->Debugoutput = 'html';
        //smtp服务器
        $mail->Host = 'smtp.qq.com';
        //端口 - likely to be 25, 465 or 587
        $mail->Port = 465;
        if($mail->Port === 465) $mail->SMTPSecure = 'ssl';// 使用安全协议
        //Whether to use SMTP authentication
        $mail->SMTPAuth = true;
        //发送邮箱
        $mail->Username = '#发送邮箱地址#';
        //密码
        $mail->Password = '#服务器认证密码#';
        //Set who the message is to be sent from
        $mail->setFrom('#发送邮箱地址#','#邮件主题#');
        //回复地址
        //$mail->addReplyTo('#回复邮箱地址#', 'First Last');
        //接收邮件方
        if(is_array($to)){
            foreach ($to as $v){
                $mail->addAddress($v);
            }
        }else{
            $mail->addAddress($to);
        }
        $mail->isHTML(true);// send as HTML
        //标题
        $mail->Subject = $subject;
        //HTML内容转换
        $mail->msgHTML($content);
        //Replace the plain text body with one created manually
        //$mail->AltBody = 'This is a plain-text message body';
        //添加附件
        //$mail->addAttachment('images/phpmailer_mini.png');
        //send the message, check for errors
        return $mail->send();
    }
}

参考地址:使用PHPMailer实现PHP发邮件功能 - 程序员-大象 - 博客园

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值