首页 > 解决方案 > 如何设置 phpmailer 使用它来发送文件

问题描述

我正在尝试学习如何使用 phpmailer,以便向用户发送附件文件并尝试关注此视频:https ://www.youtube.com/watch?v=fcLXsxpk2dc

这是我的 phpmailer 代码,但我认为我的使用文件设置正确,但找不到文件:

 <?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use phpmailer\PHPMailer\src\PHPMailer;
use phpmailer\PHPMailer\src\Exception;

//Load Composer's autoloader
require 'vendor/autoload.php';

$mail = new PHPMailer(true);                              // Passing `true` enables exceptions
try {
    //Server settings
    $mail->SMTPDebug = 2;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.live.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'piano0011@hotmail.com';                 // SMTP username
    $mail->Password = 'Grandpiano888';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 25;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('piano0011@hotmail.com', 'PianoCourse101');
    $mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient
    $mail->addAddress('ellen@example.com');               // Name is optional
    $mail->addReplyTo('info@example.com', 'Information');
    $mail->addCC('cc@example.com');
    $mail->addBCC('bcc@example.com');

    //Attachments
    $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    //Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}

它说:

致命错误:未捕获的错误:在 C:\xampp\htdocs\loginsystem\phpmailer.php:10 中找不到类 'phpmailer\PHPMailer\src\PHPMailer' 堆栈跟踪:#0 {main} 在 C:\xampp\htdocs\ 中抛出第 10 行的 loginsystem\phpmailer.php

在此处输入图像描述

标签: phpphpmailer

解决方案


你误解了use陈述的目的。它们不是路径;他们将命名空间的类名导入您当前的命名空间。将代码更改为此,如示例所示:

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

推荐阅读