phpMailer Attachment not working

11,932

Solution 1

Had the same problem, try this

$mail->AddAttachment($_SERVER['DOCUMENT_ROOT'].'/file-name.pdf');

Solution 2

First, make sure your upload form has enctype='multipart/form-data' as in <form method=post action=file.php enctype='multipart/form-data'>.

then, use this code in your phpmailer handler file

foreach(array_keys($_FILES['files']['name']) as $key) {
   $source = $_FILES['files']['tmp_name'][$key];
   $filename = $_FILES['files']['name'][$key];

   $mail->AddAttachment($source, $filename);
}
Share:
11,932
Emad Alghamdi
Author by

Emad Alghamdi

Updated on June 26, 2022

Comments

  • Emad Alghamdi
    Emad Alghamdi about 2 years

    this is my first post and I hope that I can get some help regarding adding an attachment field in my phpMailer contact form. I have already added an uploader [browse] bar in the html website but I don't know how to link it with the phpmailer. do I have to declare it at the package which is phpmailer.php or do something with it?

    I would really appreciate some help. Below is my desperate attempt.

    Snippet from the code:

    <?
    $body = ob_get_contents();
    
    $to = '[email protected]>';
    $email = $email;
    $subject = $subject;
    $fromaddress = "[email protected]";
    $fromname = "Online Contact";
    
    require("phpmailer.php"); //<<this is the original pack
    
    $mail = new PHPMailer();
    
    $mail->From     = "[email protected]";
    $mail->FromName = "My Name";
    $mail->AddBCC("[email protected]","Name 1");
    $mail->AddAddress( $email,"Name 2");
    
    $mail->WordWrap = 50;
    $mail->IsHTML(true);
    
    $mail->Subject  =  $subject;
    $mail->Body     =  $body;
    $mail->AltBody  =  "This is the text-only body";
    // attachment
    $mail->AddAttachment('uploadbar', 'new_file.pdf'); // the name of my html uploader is uploadbar, clicking browse to locate a file
    
    if(!$mail->Send()) {
        $recipient = '[email protected]';
        $subject = 'Contact form failed';
        $content = $body;   
    
      mail($recipient, $subject, $content, "From: [email protected]\r\nReply-To: $email\r\nX-Mailer: DT_formmail");
      exit;
    }
    ?>
    
  • Emad Alghamdi
    Emad Alghamdi about 12 years
    I replaced my AddAttachment line with all your lines. I still don't get any attachments in the email.
  • Emad Alghamdi
    Emad Alghamdi about 12 years
    here is the phpmailer.php which I did not include any of its code - 2shared.com/file/RcD8xdI1/phpmailer.html - What's included in my first post is the process.php
  • Ciro
    Ciro about 12 years
    in your specific case, if upload input is named uploadbar use $_FILES['uploadbar'] instead of $_FILES['files']
  • Emad Alghamdi
    Emad Alghamdi about 12 years
    still not working. I don't know if you need more information to help you or files? Thank you by the way!