Sending uploaded file via email

I have a php form which allows uploading files. However, the files go to the server and I need them to go with the rest of the form via email to the specified email address. Can someone please help?

Here is the code I am currently using, and just need to add a section to have it send the uploaded file with the email:

<?php
//--------------------------Set these paramaters--------------------------

// Subject of email sent to you.
$subject = 'Quote Form';

// Your email address. This is where the form information will be sent.
$emailadd = '';

// Where to redirect after form is processed.
$url = 'l';

// Where to direct file upload.
$file= '';

// Makes all fields required. If set to '1' no field can not be empty. If set to '0' any or all fields can be empty.
$req = '0';

// --------------------------Do not edit below this line--------------------------
$text = "Results from form:\
\
";
$space = ' ';
$line = '
';
foreach ($_POST as $key => $value)
{
if ($req == '1')
{
if ($value == '')
{echo "$key is empty";die;}
}
$j = strlen($key);
if ($j >= 20)
{echo "Name of form element $key cannot be longer than 20 characters";die;}
$j = 20 - $j;
for ($i = 1; $i <= $j; $i++)
{$space .= ' ';}
$value = str_replace('\
', "$line", $value);
$conc = "{$key}:$space{$value}$line";
$text .= $conc;
$space = ' ';
}
mail($emailadd, $subject, $text, 'From: '.$emailadd.'');
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';{
}
if ((($_FILES["file"]["type"] == "application/ai")
|| ($_FILES["file"]["type"] == "application/postscript")
|| ($_FILES["file"]["type"] == "application/cdr")
|| ($_FILES["file"]["type"] == "application/dxf")
|| ($_FILES["file"]["type"] == "applicationj/eps")
|| ($_FILES["file"]["type"] == "application/pdf"))
&& ($_FILES["file"]["size"] < 900000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

I have removed the email address and URL in the code for posting on this forum. I am fairly new to PHP and any help would be greatly appreciated! Thank you.

PHP: Sending Email (Text/HTML/Attachments)

You will use the path to your uploaded file to replace ‘attachment.zip’ in the example from the above link. You should also change the content type.

I recommend you get familiar with a PHP mail library (like PHPMailer or SwiftMailer), it will make the task of sending mail much easier.

Also you should move your code around a bit. From what I see now you are first sending the email and then process the uploaded file. You will have to process the uploaded file BEFORE sending the email.

Hope this helps.

I use a modified Codeigniter Email class:


<?php

set_time_limit(0);

require ("Email.php");

class Mailer
{
    public $email;

    public function __construct(CI_Email $email)
    {
        $this->email = $email;
    }

	private function empty_dir()
	{
		$mask = "uploads/*";

		array_map("unlink", glob($mask));
	}

    public function execute()
    {
        $this->email->from('xyz@yahoo.co.uk', '');
        $this->email->to($_POST['to']);

        /*
        $this->email->cc('another@another-example.com');
        $this->email->bcc('them@their-example.com');
        */

        $this->email->subject(@$_POST['sj']);
        $this->email->message(@$_POST['msg']);

		for($i = 0; $i < count($_FILES['file']['tmp_name']); $i++)
		{
			$file_name = $_FILES['file']['name'][$i];
			$file_type = $_FILES['file']['type'][$i];
			$tmp_name = $_FILES['file']['tmp_name'][$i];
			
			if( move_uploaded_file($tmp_name, "uploads/$file_name"))
			{
				$this->email->attach("uploads/$file_name");
			}
		}

        if ($this->email->send())
		{
			$this->empty_dir();
		}

        #$this->email->print_debugger();
    }
}

$config['protocol'] = 'sendmail';
#$config['smtp_host'] = '';

$config['smtp_host'] = '';
$config['smtp_user'] = ''; // not my actual email obviously
$config['smtp_pass'] = '';
$config['smtp_port'] = 587;
$config['mailpath'] = "D:\\send\\sendmail.exe -t";

$email = new CI_Email($config);
$mailer = new Mailer($email);

if( isset($_POST['submit']))
{
	$mailer->execute();
}

?>
</pre>
<html>
<head>
<title>Untitled Document</title>
<script type="text/javascript">
function add_file(id, i)
{
	if (document.getElementById(id + '_' + i).innerHTML.search('uploadinputbutton') == -1)
	{
		document.getElementById(id + '_' + i).innerHTML = '<input type="file" maxsize="" name="' + id + '[]" onchange="return add_file(\\'' + id + '\\', ' + (i+1) + ');" /><br /><span id="' + id + '_' + (i+1) + '"><input type="button" value="Add other" onclick="add_file(\\'' + id + '\\', ' + (i+1) + ');" /><\\/span>\
';
	}
}
</script>
</head>
<body>
 <form action="" method="post" enctype="multipart/form-data">
  <p>To: <input type="text" name="to" /></p>
  <p>Subject: <input type="text" name="sj" /></p>
  <p>Attachment:</p> <input type="file" name="file[]" onchange="add_file('file', 1);" /><br />
  <span id="file_1"><input type="button" value="Add another" onclick="add_file('file', 1);" /></span></p>
  <p>Mess: </p><textarea rows="15" cols="55" name="msg"></textarea>
  <input type="submit" name="submit" />
</form>
</form>
</body>
</html>

I found SwiftMailer very easy to implement once I’d got my head around the OOP. I’ve been able to send multiple attachments with ease.

Thank you so very much! The original code above I got from W3Schools.com and just added the upload portion…didn’t even know where to add it because I couldn’t find any help. Well, it worked (until I changed the file types to meet client’s desires) and then client told me he wanted files to be sent to his email. So, hopefully I will be able to figure this thing out.

acid24ro:

The code worked to send the attachment to me via email. However, it did not send the form results with it. Can you please advise as to how to integrate it into my code above so that I get both the form results and the attachment? I’m so lost! Thank you.

Hi,

Post the code, and I may be able to help you.

Thank you for your offer to help. However, the only thing I have been able to find does not send the form results of the form that was already developed along with the attachment. Therefore, I have purchased a Dreamweaver Widget that does this for me. I know, it’s cheating, but I had a very frustrated client and I had to do something. Thanks for all your help, I do appreciate it.