PHP send an email with image attachment

前端 未结 3 1936
情话喂你
情话喂你 2021-01-03 10:25

I\'m trying to create a script that will send an image uploaded from an iphone app I\'m developing to me in an email.

I\'ve been able to get the script to send me an

相关标签:
3条回答
  • 2021-01-03 10:25

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

    $message .= "--{$mime_boundary}--\n";
    
    0 讨论(0)
  • 2021-01-03 10:34
            // 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);          
    
    0 讨论(0)
  • 2021-01-03 10:41

    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).

    0 讨论(0)
提交回复
热议问题