user2111146
user2111146

Reputation: 13

Trying to send a mail with attachment

I have made a form that uploads an image to an upload folder. But now i need to mail the image in an attachment. I tried this

$Body .= "http://myurl.nl/upload/" . $filename . "";

Actually it doesn't matter if the image is in the attachment as long as they can download them direct from my server. So now im struggeling with the path of the file

$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 10000000)
&& in_array($extension, $allowedExts))
{
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
  {
  $filename = str_replace(' ', '', $_FILES["file"]["tmp_name"]);
  move_uploaded_file($_FILES["file"]["tmp_name"],
  "upload/" . $filename);
  echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
  }
  }
 }
else
 {
 echo "Invalid file";
 }

Upvotes: 0

Views: 2656

Answers (4)

SDC
SDC

Reputation: 14212

For goodness sake, please don't even try to use PHP's built-in mail() function for sending attachments -- it's bad enough for basic mail, but for attachments you really need to use a decent library.

There are several libraries you can use.

I suggest phpMailer. It's very easy to use, and makes adding attachments totally simple -- see this examples page to see how easy it is.

And yes, this will mean you have to throw away your existing code. This is a good thing. No offense to your code, but it certainly isn't a decent mail library. phpMailer has been in development for years, and has dealt with all the bugs and quirks that have come up in that time. If you're prepared to spend the same amount of time fixing bugs in your own code, then sure, do it yourself. If not, you really should make use of a library where someone else has already done all the hard work for you.

Upvotes: 0

amandasantanati
amandasantanati

Reputation: 331

I also would use Swiftmailer (I still use it when developing with symfony 1.4).

But just to complete this answer, Swiftmailer has some kind of issue when attaching a remote file, speifically PDF's files. It's still an open issue (https://github.com/swiftmailer/swiftmailer/issues/207). But at the end of this issue you can find an workaround, which is:

$attachment = Swift_Attachment::newInstance(file_get_contents($url_file));

I would complement it with renaming the filename or it would attach a nonane file:

$attachment = Swift_Attachment::newInstance(file_get_contents($url_file))->setFilename('arquivo.pdf');

That's it :)

Upvotes: 0

ivodvb
ivodvb

Reputation: 1164

I'd use Swiftmailer and use the the following method: http://swiftmailer.org/docs/messages.html#attaching-files

<?php

require_once 'lib/swift_required.php';

// Create the message
$message = Swift_Message::newInstance()

  // Give the message a subject
  ->setSubject('Your subject')

  // Set the From address with an associative array
  ->setFrom(array('[email protected]' => 'John Doe'))

  // Set the To addresses with an associative array
  ->setTo(array('[email protected]', '[email protected]' => 'A name'))

  // Give it a body
  ->setBody('Here is the message itself', 'text/html')

  // You can attach files from a URL if allow_url_fopen is on in php.ini
  ->attach(Swift_Attachment::fromPath('my-document.pdf'));

// If you have SMPT, use the SMTP transport(http://swiftmailer.org/docs/sending.html#using-the-smtp-transport)
// Create the Transport
$transport = Swift_MailTransport::newInstance();

// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);

// Send the message
$numSent = $mailer->send($message);

printf("Sent %d messages\n", $numSent);

/* Note that often that only the boolean equivalent of the
   return value is of concern (zero indicates FALSE)

if ($mailer->send($message))
{
  echo "Sent\n";
}
else
{
  echo "Failed\n";
}

*/

Upvotes: 2

henser
henser

Reputation: 3337

Answer taken from dqhendricks in php send email with attachment

function mail_attachment($to, $subject, $message, $from, $file) {
      // $file should include path and filename
      $filename = basename($file);
      $file_size = filesize($file);
      $content = chunk_split(base64_encode(file_get_contents($file))); 
      $uid = md5(uniqid(time()));
      $from = str_replace(array("\r", "\n"), '', $from); // to prevent email injection
      $header = "From: ".$from."\r\n"
          ."MIME-Version: 1.0\r\n"
          ."Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n"
          ."This is a multi-part message in MIME format.\r\n" 
          ."--".$uid."\r\n"
          ."Content-type:text/plain; charset=iso-8859-1\r\n"
          ."Content-Transfer-Encoding: 7bit\r\n\r\n"
          .$message."\r\n\r\n"
          ."--".$uid."\r\n"
          ."Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"
          ."Content-Transfer-Encoding: base64\r\n"
          ."Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n"
          .$content."\r\n\r\n"
          ."--".$uid."--"; 
      return mail($to, $subject, "", $header);
     }

Upvotes: 0

Related Questions