如何使用phpmailer发送附件,但我更喜欢用户mail()

时间:2018-10-21 08:29:02

标签: php

我正在尝试使用mail()添加一些附件,并且希望使用它,但是phpmailer是否确实是一个更好的选择呢?如果是这样,我正在尝试使phpmailer正常工作,但是设置了正确的require路径,但似乎找不到文件...

<?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;

require 'phpmailer/PHPMailer/src/Exception.php';
require 'phpmailer/PHPMailer/src/PHPMailer.php';
require 'phpmailer/PHPMailer/src/SMTP.php';

//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;

This是目录的路径。

但是可以使用mail()函数吗?

1 个答案:

答案 0 :(得分:1)

  

严重错误:未捕获的错误:类'phpmailer \ PHPmailer \ src \ PHPMailer'   在C:\ xampp \ htdocs \ loginsystem \ phpmailer.php:12中找不到堆栈跟踪:   (#)0 {main}在第1行的C:\ xampp \ htdocs \ loginsystem \ phpmailer.php中抛出

您当前的名称空间导入不正确

<?php
   use phpmailer\PHPMailer\src\PHPMailer; // Incorrect
   use phpmailer\PHPMailer\src\Exception; // Incorrect

将名称空间导入更改为:

<?php
   use PHPMailer\PHPMailer\PHPMailer;
   use PHPMailer\PHPMailer\Exception;