简体   繁体   中英

Correct format for sending mime-encoded email using PHP's mail

What is the correct way to create an mime multipart email for sending with PHP's mail function?

    $boundary = uniqid(rand(), true);

    $headers =  "From: <noreply@example.com>\r\n";
    $headers .= "Reply-To: <noreply@example.com>\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: multipart/alternative; boundary=$boundary\r\n\r\n";
    $headers .= "This is a MIME encoded message.\r\n\r\n";
    $headers .= "--$boundary\r\n" .
                "Content-Type: text/plain; charset=ISO-8859-1\r\n" .
                "Content-Transfer-Encoding: base64\r\n\r\n";
    $headers .= chunk_split(base64_encode($plaintext));
    $headers .= "--$boundary\r\n" .
                "Content-Type: text/html; charset=ISO-8859-1\r\n" .
                "Content-Transfer-Encoding: base64\r\n\r\n";
    $headers .= chunk_split(base64_encode($body)); // chunk_split adds the ending "\r\n"
    $headers .= "--$boundary--\r\n";
    //$headers .= ".\r\n";

    mail($to, $subject, '', $headers);

I tried the above but PHP seems to ignore it and instead sends this empty email which I receive on the server:

...
...
To: <....>
Subject: Test Email
X-PHP-Originating-Script: 0:Mail.php
From: <noreply@example.com>
Reply-To: <noreply@example.com>
MIME-Version: 1.0
Content-Type: multipart/alternative;
    boundary="1923630041519679ed1ddd25.14582240"
Message-ID: <20130517184149.28AB0A4C4@example.com>
Date: Fri, 17 May 2013 14:41:49 -0400
X-UI-Loop: V01:211ZxL2TMQ4=:uQC6SYy+5ULsBgI8/Yn6FAKnX8a66b5mzBQJFWhGo82c
 3a8ZtvbDIKAYJ3vIkfg3

--1923630041519679ed1ddd25.14582240
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: base64


--1923630041519679ed1ddd25.14582240
Content-Type: text/html; charset="ISO-8859-1"
Content-Transfer-Encoding: base64


--1923630041519679ed1ddd25.14582240--

Tested on PHP 5.4.9.

I got the above code working. Seems I needed to replace all the windows \\r\\n with linux \\n . I also removed the duplicate newlines after the boundary="..." .

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