PHP отправить письмо с приложением - PullRequest
2 голосов
/ 22 июня 2010

Кажется, я не могу найти проблему с этой функцией php, которую я написал, которая должна отправить электронное письмо с вложением. Я долго боролся с этим.

function myMail($to, $subject, $mail_msg, $filename, $contentType){

    $random_hash = md5(date('r', time()));
    $headers = "From: webmaster@example.com\r\nReply-To: ".$to;
    $headers .= "\r\nContent-Type: ".$contentType.
        "; boundary=\"PHP-mixed-".$random_hash."\"";

    $attachment = chunk_split(base64_encode(file_get_contents($filename)));
    ob_start();

    echo "
--PHP-mixed-$random_hash
Content-Type: multipart/alternative; boundary=\"PHP-alt-$random_hash\"

--PHP-alt-$random_hash
Content-Type: text/plain; charset=\"utf-8\"
Content-Transfer-Encoding: 7bit

$mail_msg

--PHP-alt-$random_hash

--PHP-mixed-$random_hash--
Content-Type: text/plain; name=\"$filename\" 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 

$attachment
--PHP-mixed-$random_hash--
";
    $message = ob_get_clean();
    $mail_sent = @mail( $to, $subject, $message, $headers );
    return $mail_sent ? "Mail sent" : "Mail failed";
}

Редактировать Проблема в том, что сообщение почты смешивается с файлом и отправляется в виде вложения.

Ответы [ 4 ]

10 голосов
/ 22 июня 2010

Я только что просмотрел несколько своих электронных писем и заметил, что окончательная граница вложения заканчивается на «-», а маркер открытой границы - нет.В вашем коде у вас есть:

--PHP-mixed-$random_hash--
Content-Type: text/plain; name=\"$filename\" 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 

$attachment
--PHP-mixed-$random_hash--

Возможно, это должно быть:

--PHP-mixed-$random_hash
Content-Type: text/plain; name=\"$filename\" 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 

$attachment
--PHP-mixed-$random_hash--

Посмотрите на пример здесь:

http://en.wikipedia.org/wiki/MIME#Multipart_messages

6 голосов
/ 22 июня 2010

Artefacto заставил меня посмотреть на результат с большим вниманием, и я нашел исправление:

function myMail($to, $subject, $mail_msg, $filename, $contentType, $pathToFilename){
    $random_hash = md5(date('r', time()));
    $headers = "From: webmaster@mysite.com\r\nReply-To: ".$to;
    $headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
    $attachment = chunk_split(base64_encode(file_get_contents($pathToFilename)));
    ob_start();
 echo "
--PHP-mixed-$random_hash
Content-Type: multipart/alternative; boundary=\"PHP-alt-$random_hash\"

--PHP-alt-$random_hash
Content-Type: text/plain; charset=\"utf-8\"
Content-Transfer-Encoding: 7bit

$mail_msg

--PHP-alt-$random_hash--

--PHP-mixed-$random_hash
Content-Type: $contentType; name=\"$filename\" 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 

$attachment
--PHP-mixed-$random_hash--
";
$message = ob_get_clean();
$fh=fopen('log.txt','w');
fwrite($fh,$message);
$mail_sent = @mail( $to, $subject, $message, $headers );
return $mail_sent ? "Mail sent" : "Mail failed";
}
3 голосов
/ 22 июня 2010

Если вы не делаете это, чтобы узнать о внутренней работе писем MIME, стандартный ответ - использовать почтовую библиотеку, такую ​​как PHPMailer или Swiftmailer , которая может работать с вложениями из коробка.

SwiftMailer Примеры того, как прикреплять файлы: здесь .

1 голос
/ 11 августа 2012

Это заголовки, которые я использую, и они всегда работали как шарм.

$base = basename($_FILES['upload']['name']);
$file = fopen($randname_path,'rb');
$size = filesize($randname_path);
$data = fread($file,$size);
fclose($file);
$data = chunk_split(base64_encode($data));

//boundary
$div = "==Multipart_Boundary_x".md5(time())."x";
//headers
$head = "From: $from\n".
        "MIME-Version: 1.0\n".
        "Content-Type: multipart/mixed;\n".
        " boundary=\"$div\"";
//message
$mess = "--$div\n".
        "Content-Type: text/plain; charset=\"iso-8859-1\"\n".
        "Content-Transfer-Encoding: 7bit\n\n".
        "$message\n\n".
        "--$div\n".
        "Content-Type: application/octet-stream; name=\"$base\"\n".
        "Content-Description: $base\n".
        "Content-Disposition: attachment;\n".
        " filename=\"$base\"; size=$size;\n".
        "Content-Transfer-Encoding: base64\n\n".
        "$data\n\n".
        "--$div\n";
$return = "-f$from";

http://asdlog.com/Create_form_to_send_email_with_attachment

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...