php 邮件发送 phpmailer

1、邮箱设置
申请账号(网易126、网易163、QQ邮箱等),在邮箱设置->POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务中开启SMTP服务,并获取授权码(授权码是用于登录第三方邮件客户端的专用密码。)
2、安装PHPMailer
composer require phpmailer/phpmailer
git :https://github.com/PHPMailer/PHPMailer
3、PHP代码调用发送邮件

<?php
namespace app\admin\controller;

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

class SendEmail
{
    protected $config = [
        'host' => 'smtp.126.com', // SMTP服务器,网易提供
        'username' => 'user@126.com', // 邮箱用户名
        'password' => 'mysecret', // 授权码
        'port' => '25' // 服务器端口,网易提供
    ];
    protected $mail;

    public function __construct($config = [])
    {
        if(!empty($config)) $this->config = $config;
        $mail = new PHPMailer(true);
        $mail->SMTPDebug = SMTP::DEBUG_SERVER;
        $mail->isSMTP();
        $mail->Host       = $this->config['host'];
        $mail->SMTPAuth   = true;
        $mail->Username   = $this->config['username'];
        $mail->Password   = $this->config['password'];
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = $this->config['port'];
        $this->mail = $mail;
    }

    public function send(){
        $mail = $this->mail;
        try {
            $mail->setFrom('from@126.com', 'Mailer'); // 设置发件人
            $mail->addAddress('joe@example.net', 'Joe User');     // 添加收件人
            $mail->addAddress('to@qq.com');               // 添加收件人
            $mail->addReplyTo('info@example.com', 'Information'); // 回复
            $mail->addCC('cc@example.com'); // 抄送
            $mail->addBCC('bcc@example.com'); // 密送

            // 附件
            $mail->addAttachment('/var/tmp/file.tar.gz');
            $mail->addAttachment('/tmp/image.jpg', 'new.jpg');

            // 邮件内容
            $mail->isHTML(true);
            $mail->Subject = '标题';
            $mail->Body    = '<p>HTML邮件客户端邮件正文</p> ';
            $mail->AltBody = '非HTML邮件客户端的纯文本正文';

            $mail->send();
            echo '已发送';
        } catch (Exception $e) {
            echo "发送失败: {$mail->ErrorInfo}";
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。