PHP Mailer:我在尝试通过表单上传文件并将其作为附件发送时收到错误“无法访问文件”

时间:2017-12-29 07:00:35

标签: php html phpmailer

这是PHP代码 我可以发邮件了。如果我注释掉$ _FILES ['attachment'] ['name'];

$conn = new mysqli($servername, $username, $password, $dbname); 
$category = $_POST['category'];
$attachment = $_FILES['attachment']['name'];
$query = "select Name, email, status, category from mailer where status='subscribed' and category='$category'";
$result = $conn->query($query);

while($row = $result->fetch_assoc()) {
    $name = $row['Name'];
    $email = $row['email'];
    $status = $row['status'];
    $category1 = $row['category'];


    require 'vendor/autoload.php';
    $mail = new PHPMailer(true);                              
    try {                               
         //send code
        //Recipients
        $mail->addAddress($email);
        $mail->AddAttachment($attachment);

3 个答案:

答案 0 :(得分:0)

$attachment = $_FILES['attachment']['name'];更改为$attachment = $_FILES['attachment']['tmp_name'];,因为name表示原始文件名,tmp_name表示服务器上的(临时)文件路径。您需要在AddAttachment()调用中指定服务器上的文件。

答案 1 :(得分:0)

    $message = 'This for sending an attachment by using php mailer';
    $Sender = 'youremail@xyz.com';      
    $subject = "Attachment Test";
    $Recipiant = 'recipient@xyz.com';
    $subject = $subject;
    $host= "yourdomain.com"; // sets GMAIL as the SMTP server
    $port=465; // set the SMTP port for the GMAIL server
    $username="info@yourdomain.com";                   // GMAIL username
    $pwd="domain mail password";

    include 'phpmailer/class.phpmailer.php';
    $mail = new PHPMailer();

    $mail->IsSMTP();
    $mail->IsMail();
    $mail->SMTPAuth   = true;                  // enable SMTP authentication
    $mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
    $mail->Host       = $host;      // sets GMAIL as the SMTP server
    $mail->Port       = $port;                   // set the SMTP port for the GMAIL server
    $mail->Username   = $username;  // GMAIL username
    $mail->Password   = $pwd;            // GMAIL password
    $mail->AddReplyTo($Sender,"");
    $mail->From       = $Sender;
    $mail->FromName   = $SenderName;
    $mail->Sender     = $Sender;
    $mail->Subject    = $subject;

    $FileName = 'PRO1158.pdf';

    $mail->Body       = "<br>".$message."<br>";

    if($FileName!=""){
        $mail->AddAttachment("Invoices/".$FileName); // attach files
    }

    $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
    $mail->WordWrap   = 50; // set word wrap
    //$mail->MsgHTML($body);
    $mail->AddAddress("$Recipiant","");
    $mail->IsHTML(true); // send as HTML
    $mail->Send();
    $mail->ClearAddresses();

答案 2 :(得分:-1)

首先,您需要将文件上传到文件夹,然后将文件路径放入  $mail->AddAttachment();

exapmle:

$attachment="D:\uploads\img.jpg"
$mail->AddAttachment($attachment);