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代码调用发送邮件

 'smtp.126.com', // SMTP服务器,网易提供
        'username' => '[email protected]', // 邮箱用户名
        '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('[email protected]', 'Mailer'); // 设置发件人
            $mail->addAddress('[email protected]', 'Joe User');     // 添加收件人
            $mail->addAddress('[email protected]');               // 添加收件人
            $mail->addReplyTo('[email protected]', 'Information'); // 回复
            $mail->addCC('[email protected]'); // 抄送
            $mail->addBCC('[email protected]'); // 密送

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

            // 邮件内容
            $mail->isHTML(true);
            $mail->Subject = '标题';
            $mail->Body    = '

HTML邮件客户端邮件正文

'; $mail->AltBody = '非HTML邮件客户端的纯文本正文'; $mail->send(); echo '已发送'; } catch (Exception $e) { echo "发送失败: {$mail->ErrorInfo}"; } } }

你可能感兴趣的:(php 邮件发送 phpmailer)