File attachment with PHPMailer

前端 未结 2 1373
无人共我
无人共我 2021-01-05 03:08

I have an HTML form with the option to upload a file.
I would like then to send that file as an attachment to the email address along with the rest of the form data.

相关标签:
2条回答
  • 2021-01-05 03:28
    $mail->addAttachment("uploads/".$file_name);
    

    Just use above code before php mailer send function

    0 讨论(0)
  • 2021-01-05 03:41

    When you call

    move_uploaded_file($file_tmp,"uploads/".$file_name);
    

    This creates a file in the uploads/ directory with the name of the file as it was named on the uploader's computer.

    Then you used sample code to add the attachment to phpMailer so you're basically attempting to attach non-existent files.

    These two lines:

    $mail->addAttachment('uploads/file.tar.gz');   // I took this from the phpmailer example on github but I'm not sure if I have it right.      
    $mail->addAttachment('uploads/image.jpg', 'new.jpg');
    

    should be changed to:

    $mail->addAttachment("uploads/".$file_name);
    

    Also note, it isn't necessary to call move_uploaded_file if you don't want to save the attachment after its uploaded and emailed. If that's the case just call AddAttachment with $_FILES['image']['tmp_name'] as the file argument.

    Also, in your HTML form, you have

    <input id="file" name="file" type="file" />
    

    but refer to the input as image in the code. You should change the name of that input from file to image.

    To only attach the image and not save it take out the move_uploaded_file code and add:

    $file_tmp  = $_FILES['image']['tmp_name'];
    $file_name = $_FILES['image']['name'];
    //...
    $mail->AddAttachment($file_tmp, $file_name);
    
    0 讨论(0)
提交回复
热议问题