简体   繁体   中英

How to attach file to email from PC using PHPMailer

I have problem when I'm trying to send e-mail via form on my website with file attached. I'm using PHPMailer, mail is always sent, but always without attached file.

I have no idea what should I fix or add to my code.

I've been looking on some tutorials, how to use PHPMailer and attach files.

Code is below:

HTML:

<form action="" method="post" enctype="multipart/form-data">
<input type="text" name="name" style="width: 70%;" placeholder="Name"><br />
<input type="text" name="email" style="width: 70%;" placeholder="Email"><br />
<input type="text" name="phone" style="width: 70%;" placeholder="Phone"><br />
<input type="file" name="fileToUpload" id="fileToUpload"><br />
<input type="submit" name="send" id="gobutton" value="Send">
</form>

PHP:

  <?
require_once("phpmailer/class.phpmailer.php");

if (isset($_POST['odeslat'])){
  $allowedExts = array("doc", "docx", "xls", "xlsx", "pdf");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "application/pdf")
|| ($_FILES["file"]["type"] == "application/msword")
|| ($_FILES["file"]["type"] == "application/excel")
|| ($_FILES["file"]["type"] == "application/vnd.ms-excel")
|| ($_FILES["file"]["type"] == "application/x-excel")
|| ($_FILES["file"]["type"] == "application/x-msexcel")
|| ($_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
|| ($_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))

&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "<script>alert('Error: " . $_FILES["file"]["error"] ."')</script>";
    }
  else
    {
        $d='upload/';
        $de=$d . basename($_FILES['file']['name']);
    move_uploaded_file($_FILES["file"]["tmp_name"], $de);
$fileName = $_FILES['file']['name'];
    $filePath = $_FILES['file']['tmp_name'];
     //add only if the file is an upload
     }
  }
else
  {
  echo "<script>alert('Invalid file')</script>";
  }

$to = $_POST['email'];
$name = $_POST['name'];
$phone = $_POST['phone'];
$mail = new PHPMailer();



$mail->From = "info@mywebsite.com";
$mail->FromName = "My website";



$mail->addAddress("mail@mail.com");
$mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']);


$mail->isHTML(true);

$mail->Subject = "Subject Text";
$mail->Body = "<i>Mail body in HTML</i>";
$mail->AltBody = "This is the plain text version of the email content";

if(!$mail->send()) 
{
   header ("Location: /?e=1");
} 
else 
{
header ("Location: /?s=1");
}
}
?>

If you do not care about the need to keep the file on the system, you can directly send the file like this :

if (isset($_FILES['fileToUpload']) &&
  $_FILES['fileToUpload']['error'] == UPLOAD_ERR_OK) {

  //check MIME TYPE
  $finfo = new finfo(FILEINFO_MIME_TYPE);
  if (false === $ext = array_search(
    $finfo->file($_FILES['fileToUpload']['tmp_name']),
    array(
        'jpg' => 'image/jpeg',
        'png' => 'image/png',
        'gif' => 'image/gif',
    ),
    true
  )) {
      throw new RuntimeException('Invalid file format.');
  }
  $destination = sprintf('./uploads/%s.%s',
       sha1_file($_FILES['fileToUpload']['tmp_name']),
       $ext
  );

  //move the file to a temp folder
  if (!move_uploaded_file(
    $_FILES['fileToUpload']['tmp_name'],
    $destination
  )) {
    throw new RuntimeException('Failed to move uploaded file.');
  }

  //Attach file
  $mail->AddAttachment($_FILES['fileToUpload']['tmp_name'],
                     basename($destination));
  //delete the file
  unlink($destination);
}

This subject has already been treated

Send File Attachment from Form Using phpMailer and PHP

Basicly you need the tmp name that was uploaded to your server and the name of the file

$_FILES['uploaded_file']['tmp_name']
$_FILES['uploaded_file']['name']

What you're doing, and what is suggested in other answers, is horribly wrong.

If you have no clue about things like this, perhaps you should try reading the docs first ?

Using $_FILES properties directly has security implications that are mitigated by using move_uploaded_file , which you are avoiding for no apparent reason.

There is an example provided with PHPMailer that does exactly what you ask, but without the security holes. To paraphrase the most important part:

if (array_key_exists('fileToUpload', $_FILES)) {
    $uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['fileToUpload']['name']));
    if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) {
        $mail->addAttachment($uploadfile, 'My uploaded file');
    }
}

For a more thorough implementation of validating uploads before using them, see this comment in the PHP docs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM