12

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.
I'm using PHP Mailer and I get the form data to send: such as name, telephone number, etc.

I can't get the image to send along with it. I've provided the code I have so far

<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>

<body>

<form id='contactus' action='contact.php' enctype="multipart/form-data" method='post'>

<fieldset >
<legend>Contact us</legend>


<div class='container'>
  
    <label for='email' >Name*:</label><br/>
    <input type="text" id="name" name="name" required /><br>
    <label for='email' >Phone*:</label><br/>
    <input type="text" id="phone" name="phone" required /><br>
    <label for='email' >Email*:</label><br/>
    <input type='text' name='email' id='email' required/><br/>
 
    <label for='message' >Message:</label><br/>
    <textarea rows="10" cols="50" name='message' id='message'></textarea>
    <br>
    <!-- Name of input element determines name in $_FILES array -->
    Send this file: <input id="file" name="image" type="file" />
    <input type='submit' name='Submit' value='Submit' />
</div>

</fieldset>
</form>
    </body>
</html>

<?php
   if(isset($_FILES['image'])){
      $errors= array();
      $file_name = $_FILES['image']['name'];
      $file_size = $_FILES['image']['size'];
      $file_tmp = $_FILES['image']['tmp_name'];
      $file_type = $_FILES['image']['type'];
      $file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
      
      $expensions= array("jpeg","jpg","png","pdf");
      
      if(in_array($file_ext,$expensions)=== false){
         $errors[]="extension not allowed, please choose a PDF, JPEG or PNG file.";
      }
      
      if($file_size > 2097152) {
         $errors[]='File size must be excately 2 MB';
      }
      
      if(empty($errors)==true) {
         move_uploaded_file($file_tmp,"uploads/".$file_name); //The folder where you would like your file to be saved
         echo "Success";
      }else{
         print_r($errors);
      }
   }

// PHPMailer script below

$email = $_REQUEST['email'] ;
$name = $_REQUEST['name'] ;
$phone = $_REQUEST['phone'] ;
$message = $_REQUEST['message'] ;
require("phpmailer/PHPMailerAutoload.php");

$mail = new PHPMailer();

$mail->IsSMTP();

$mail->Host = "smtp.gmail.com";

$mail->SMTPAuth = true; 

$mail->Username = "yoursmtp@username.com"; // SMTP username
$mail->Password = "hidden"; // SMTP password
$mail->addAttachment("uploads/".$file_name);
$mail->From = $email;
$mail->SMTPSecure = 'tls'; 
$mail->Port = 587; //SMTP port
$mail->addAddress("your@email.com", "your name");
$mail->Subject = "You have an email from a website visitor!";
$mail->Body ="
Name: $name<br>
Email: $email<br>
Telephone: $phone<br><br><br>
Comments: $message";
$mail->AltBody = $message;

if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}

echo "<script>alert('Message has been sent')</script>";
?>

EDIT: [SOLVED] I have updated the code in the snippets to the working code that allows me to attach a file with to an email with PHPMailer.
I used This Tutorial to help upload the file to the server before executing the PHPMailer script.

Community
  • 1
  • 1
Eli Nathan
  • 854
  • 1
  • 9
  • 29
  • You've based your code on an obsolete example, so make sure you're using the latest version of PHPMailer. – Synchro Mar 14 '16 at 22:20
  • I'm using the latest version from github – Eli Nathan Mar 14 '16 at 22:35
  • Ok, so why base your code on an obsolete example? – Synchro Mar 15 '16 at 09:13
  • I'd appreciate if you could be clearer on what exactly is obsolete? I have looked at all the up to date examples on github and my code is the same. If you could maybe help that'd be great. – Eli Nathan Mar 15 '16 at 10:29
  • 2
    All PHPMailer methods were changed to use lower-case starting characters, and `WordWrap` was removed from all examples well over a year ago. Brackets around the autoloader require and double-quoted params were removed ages ago too. You're connecting to gmail without using encryption - I don't think the gmail example provided with PHPMailer has ever left that out. There is nothing specifically wrong with those things, but when I see little indicators like that, it suggests that the code is either old or has been obtained elsewhere, and often means that an old version is in use. – Synchro Mar 15 '16 at 11:00
  • Thanks! I'll change those aspects back to the original example from GitHub. I must have changed them slightly when searching for other examples. I don't suppose you know why any of the code would be stopping a file from being uploaded and attached to the email? I've tried changing the file permissions on my server to allow users to write but it hasn't helped. – Eli Nathan Mar 15 '16 at 11:29
  • *EDIT: [SOLVED]* — Don't do that. Questions are for questions. Answers are for answers. See also [How does accepting an answer work](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work). – Quentin Mar 15 '16 at 20:03

2 Answers2

32

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);
drew010
  • 67,054
  • 11
  • 128
  • 154
  • Thanks for the comment! Well spotted with the input name! It still isn't sending the file along with the email though – Eli Nathan Mar 14 '16 at 21:41
  • Can you confirm that `uploads/file` gets created where `file` is the name of the file you uploaded? – drew010 Mar 14 '16 at 23:35
  • No it doesn't, I don't need the file to be saved to the server, could you expand more on: "If that's the case just call addAttachment with $_FILES['image']['tmp_name'] as the file argument." Thanks! – Eli Nathan Mar 15 '16 at 07:09
  • I just edited it to show how to do it without move_uploaded_file. Hope that helps. – drew010 Mar 15 '16 at 07:15
  • Still no dice! I really appreciate the help btw I'm thinking maybe the problem is lying with the file not actually uploading to anywhere temporarily. When I upload a file, Chrome shows me a progress report at the bottom of the screen e.g 50% > 90%, so I know the browser is in fact registering that the file is being uploaded But when it tries to grab the file and attach it, nothing happens Here is the link incase you can see anything useful www.elisweb.co.uk/form – Eli Nathan Mar 15 '16 at 07:50
  • Take a look at [this answer](http://stackoverflow.com/questions/11764156/send-file-attachment-from-form-using-phpmailer-and-php/11764230#11764230). It's pretty much exactly what you're trying to do. Also you can check `$_FILES['image']['error']` to make sure there are no PHP errors with the file upload. – drew010 Mar 15 '16 at 15:15
  • Yeah I've tried that one, I'll go back and try again though! I'd upvote your answer for all the help you've given me but my rep isn't high enough yet I'm quite new to stack-overflow so I'm not sure what to do about marking the answer as correct. Since you corrected my code, I would mark your answer as correct, or would that be misleading since I'm still having problems?? – Eli Nathan Mar 15 '16 at 15:52
  • Do you want to edit your original post with the code you have currently and I can spot if anything is wrong with it that might be causing the upload not to work? – drew010 Mar 15 '16 at 17:07
  • 1
    I finally managed! Thanks Drew! I had the code wrong for uploading the file to the server. I used this [link](http://www.tutorialspoint.com/php/php_file_uploading.htm) to help me with that and your answer to fix the code in my HTML and PHPMailer script – Eli Nathan Mar 15 '16 at 20:07
0
$mail->addAttachment("uploads/".$file_name);

Just use above code before php mailer send function

Dima Kozhevin
  • 3,371
  • 9
  • 37
  • 51