Shane Buckley Shane Buckley - 1 year ago 99
PHP Question

PHP Multiple file upload then attach inline to email via PHPMailer

I'm having a spot of bother with PHPMailer and have searched high and low for this information but nada.

Basically I have a form where the user can upload multiple images which are then saved to a folder on my server, then I need to send an email with the images attached inline at the bottom of the email via PHPMailer.

I can get it to put the first image as inline but the rest of the images do not appear..

Some code:

require '../PHPMailer/PHPMailerAutoload.php';

$mail = new PHPMailer;

if(count($_FILES['upload']['name']) > 0){
//Loop through each file
for($i=0; $i<count($_FILES['upload']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];

//Make sure we have a filepath
if($tmpFilePath != ""){

//save the filename
$shortname = $_FILES['upload']['name'][$i];

//save the url and the file
$filePath = "../reports/".$id."/" . date('d-m-Y-H-i-s').'-'.$_FILES['upload']['name'][$i];

//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $filePath)) {

$files[] = $shortname;
//insert into db
//use $shortname for the filename
//use $filePath for the relative url to the file

$mail->AddEmbeddedImage($filePath, $shortname, $shortname);
$atts = '<img src="cid:'.$shortname.'">';

$mail->Body .= $atts;

Answer Source


$dir2 = opendir('../reports/'.$id);  // Open the directory containing the uploaded files.

$files = array();
while ($files[] = readdir($dir2));

foreach ($files as $file) {

      if ($file != "." && $file != ".." && $file != 'resources' ){
      $withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $file);
      $url = '../reports/'.$id.'/'.$file;
      $mail->AddEmbeddedImage($url, $withoutExt);
      $mail->Body .= '<img src="cid:'.$withoutExt.'">';