PHP: mail (), прикрепляющий изображение base64, выходит в виде текста - PullRequest
2 голосов
/ 11 августа 2011

Я пытался закодировать изображение как base64, а затем отправил его как вложение электронной почты, используя php mail (), но все, что я получаю, - это текст base64 в моей электронной почте. Вот что я использую:

$boundary1 = 'bound1';
$boundary2 = 'bound2';
$to = 'test@me.com';  
$subject = 'Test Image attachment'; 
$headers = 'From: "Me" <me@myemail.com>'."\r\n"; 
//add boundary string and mime type specification 
$headers .= "MIME-Version: 1.0\r\n"; 
$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary1\""; 
//define the body of the message. 
$message = 'Content-Type: image/png; name="'.$file_name.'"'."\n"; 
$message .= "Content-Transfer-Encoding: base64\n"; 
$message .= "Content-Disposition: inline; filename=\"$file_name\"\n\n";
$message .= base64_encode_image("signature_files/".$file_name, 'png')."\n";
$message .= "--" . $boundary2 . "\n";
//send the email 
mail( $to, $subject, $message, $headers);

// Function to encode an image
function base64_encode_image($filename=string,$filetype=string) {
    if ($filename) {
        $imgbinary = fread(fopen($filename, "r"), filesize($filename));
        return 'data:image/' . $filetype . ';base64,' . chunk_split(base64_encode($imgbinary), 64, "\n");
    }
}

Кто-нибудь видит что-то не так с этим кодом? На самом деле не уверен, почему я просто вижу текст RAW, когда получаю письмо.

1 Ответ

0 голосов
/ 11 августа 2011

Вы смешиваете \r\n и \n\n в заголовках сообщений и заголовках частей вложений MIME соответственно. Попробуйте изменить их все на \r\n.

Еще одна возможность - если вы пытаетесь прикрепить изображение, а не отображать его в строке, используйте Content-disposition: attachment;

$message .= "Content-Disposition: attachment; filename=\"$file_name\"\n\n";
...