PHP send an email with image attachment

半城伤御伤魂 提交于 2019-11-30 16:07:32
mti2935
        // to, from, subject, message body, attachment filename, etc.
        $to = "to@to.com";
        $from = "from@from.com";
        $subject = "subject";
        $message = "this is the message body";
        $filename = "/home/user/file.jpeg";
        $fname = "file.jpeg";

        $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 = "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"; 
        $message .= "--{$mime_boundary}\n";

        // preparing attachments            
            $file = fopen($filename,"rb");
            $data = fread($file,filesize($filename));
            fclose($file);
            $data = chunk_split(base64_encode($data));
            $message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"".$fname."\"\n" . 
            "Content-Disposition: attachment;\n" . " filename=\"$fname\"\n" . 
            "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
            $message .= "--{$mime_boundary}--\n";


        // send
        //print $message;

        $ok = @mail($to, $subject, $message, $headers, "-f " . $from);          
Dan Ross

While there are canned functions for this, what a fantastic exercise for a junior programmer!

Very well written mti2935. It would do folks good to actually read and not just cut-and-paste. If you're sending email with php, you should understand these fundamental concepts.

Probably some oversights from masking your real code:

Line 23 should be:

$data = fread($file,filesize($filename));

That is, $fname should be $filename.

Line 26 should be:

$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"".$fname."\"\n" .

Neither $x nor $files[$x] are defined.

@Thomas Spade: I'd like to remind that you should always sanitize input (email address).

Siebren

And the closing mime boundary should end in --, so line 29 should read:

$message .= "--{$mime_boundary}--\n";
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!