Send an email attachment with PHP


March 9th, 2009

To send email attachments you need to make use of MIME (Multipurpose Internet Mail Extensions) – a mechanism that allows email to go beyond a basic, limited character set. MIME has many uses but for the purposes of this tutorial we will send a multipart/mixed MIME email; this means we can send a text email and attach a PDF file to it (for information on attaching other file types please see the end of this tutorial).

Code listing

Here’s the complete code listing.

// Settings
$name = "Name goes here";
$email = "someome@anadress.com";
$to = "$name <$email>";
$from = "John-Smith ";
$subject = "Here is your attachment";
$fileatt = "./test.pdf";
$fileatttype = "application/pdf";
$fileattname = "newname.pdf";
$headers = "From: $from";

// File
$file = fopen($fileatt, 'rb');
$data = fread($file, filesize($fileatt));
fclose($file);

// This attaches the file
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$message = "This is a multi-part message in MIME format.\n\n" .
"-{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message .= "\n\n";

$data = chunk_split(base64_encode($data));
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatttype};\n" .
" name=\"{$fileattname}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileattname}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"-{$mime_boundary}-\n";

// Send the email
if(mail($to, $subject, $message, $headers)) {

    echo "The email was sent.";

}
else {

    echo "There was an error sending the mail.";

}

You can attach any kind of file you like – you need to make sure that change the $fileatttype variable to reflect the content type of the file you are attaching (e.g. image/gif for a GIF file).

I had problems with this code when I moved the post over to WordPress. Thanks a million to Mike Cooper for pointing this out—and helping me to fix it.

To use me in a web project call me on 07843 483 078 or get a free quote now!

2 Responses to “Send an email attachment with PHP”

  1. asy1mpo says:

    Is it possible to do a form, where the visitor can click a browser button. Find a file on computer e.g. PDF and when they click Send the form AND the PDF are emailed to someone?

  2. admin says:

    Yes.

    This script shows you how to mail a file on your server as an attachment. So, to do what you are asking all you need to do is upload the file first THEN use this script. In fact, if you attach the temporary uploaded file and don’t bother moving it anywhere, you wouldn’t even have to worry about deleting it afterwards.

Leave a Reply

You must be logged in to post a comment. If you don't have an account register one now.