Emad Alghamdi
Emad Alghamdi

Reputation: 11

phpMailer Attachment not working

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

Upvotes: 1

Views: 13916

Answers (3)

Harikaran K
Harikaran K

Reputation: 428

Make sure attachment file name should not contain any special character and check the file path also correct.

eg: [file name.pdf] Should be like [filename.pdf]

Upvotes: 0

Dah Problum
Dah Problum

Reputation: 141

Had the same problem, try this

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

Upvotes: 8

Ciro
Ciro

Reputation: 662

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);
}

Upvotes: 2

Related Questions