简体   繁体   中英

attach file to email using php

I have an input on my form to allow a user to browse to a file location. The idea being that they can attach a resume to to the application they are getting ready to submit.

<label class="description" for="element_5">Upload a File </label>
        <div>
            <input id="element_5" name="element_5" class="element file" type="file"/> 

For my text feilds and dropdowns I have been using something along the lines of:

$experince = $_POST["experince"];

But I don't want the path string i want the actual file. How do I get the file itself and how do I attach it to the email?

Also, is there a easy way to limit the attachment to .DOC / .PDF?

I did something similar to this recently. It is not trivial.

Your email message will have to be a multipart Mime message. You will read in your file, encode it (using base64), then place it in your email message string in the correct spot.

This looks like a decent tutorial (that I wish I had found before): http://www.texelate.co.uk/blog/send-email-attachment-with-php/

But note that the tutorial has some escape issues:

$message . "“nn";

should be:

$message . "\n\n";

You can also look into the Mail_Mime PEAR package for help: http://pear.php.net/package/Mail_Mime

Take a look at

Here is what I have done to send a mail with an attachment. Some of the code is mine and some of it has been taken from http://php.net/manual/en/function.mail.php . This code has been tried and tested so, it should work. Also see if sendmail is installed. If on linux ubuntu system try sudo apt-get install sendmail to install it. The best part about this code is that it works for multiple file uploads.

File Name: index.php

<?php
if( $_POST || $_FILES )
{
    // email fields: to, from, subject, and so on
    // Here 
    $from = "someone@somewhere.com";
    $to = "someone_else@somewhere_else.com";
    $subject = "Mail with Attachment";
    $message = "This is the message body and to it I will append the attachments.";
    $headers = "From: $from";

    // boundary
    $semi_rand = md5(time());
    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

    // headers for attachment
    $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";

    // multipart boundary
    $message = "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n"."Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
    fixFilesArray($_FILES['attachment']);
    foreach ($_FILES['attachment'] as $position => $file) 
    {
        // should output array with indices name, type, tmp_name, error, size
        $message .= "--{$mime_boundary}\n";
        $fp     = @fopen($file['tmp_name'],"rb");
        $data   = @fread($fp,filesize($file['tmp_name']));
        @fclose($fp);
        $data = chunk_split(base64_encode($data));
        $message .= "Content-Type: application/octet-stream; name=\"".$file['name']."\"\n"."Content-Description: ".$file['name']."\n" ."Content-Disposition: attachment;\n" . " filename=\"".$file['name']."\";size=".$file['size'].";\n"."Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
    }
    $message .= "--{$mime_boundary}--";
    $returnpath = "-f" . $from;
    $ok = @mail($to, $subject, $message, $headers, $returnpath);
    if($ok){ return 1; } else { return 0; }
}
//This function will correct file array from $_FILES[[file][position]] to $_FILES[[position][file]] .. Very important

function fixFilesArray(&$files)
{
    $names = array( 'name' => 1, 'type' => 1, 'tmp_name' => 1, 'error' => 1, 'size' => 1);

    foreach ($files as $key => $part) {
        // only deal with valid keys and multiple files
        $key = (string) $key;
        if (isset($names[$key]) && is_array($part)) {
            foreach ($part as $position => $value) {
                    $files[$position][$key] = $value;
            }
            // remove old key reference
            unset($files[$key]);
        }
    }
}
?>
<html>
    <body>
        <form method="POST" action="index.php" enctype="multipart/form-data">
            <input type="file" name="attachment[]"><br/>
            <input type="submit">
        </form>
    </body>
</html>

By the way, I would like to apologize for using sendmail since it is a bit slow. I will try to post a better solution.

This is what i have so far but its not working

<input id="resumeup" name="resumeup"  type="file"/> 

<?php $_FILES = $_POST["resumeup"];

            if ((($_FILES["file"]["type"] == "image/gif")
            || ($_FILES["file"]["type"] == "image/jpeg")
            || ($_FILES["file"]["type"] == "image/pjpeg"))
            && ($_FILES["file"]["size"] < 20000))
            {
                if ($_FILES["file"]["error"] > 0)
                {
                    echo "Error: " . $_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 "Stored in: " . $_FILES["file"]["tmp_name"];
                }
            } ?>

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