You want to send an attachment along with your mail message.

Technique

Use a boundary to separate the body of your message with the attachment:

<?php
$boundary = "b" . md5(uniqid(time()));
$mime =  "Content-type: multipart/mixed; ";
$mime .= "boundary = $boundaryrnrn";
$mime .= "This is a MIME encoded message.rnrn";
// First the regular message
$mime_message .= "--$boundaryrn";
$mime .= "Content-type: text/plainrn";
$mime .= "Content-Transfer-Encoding: base64";
$mime .= "rnrn" . chunk_split(base64_encode($message)) . "rn";
// Now the attachment
$filename = "data.txt";
$attach = chunk_split(base64_encode(implode("", file($filename))));
$mime .= "--$boundaryrn";
$mime .= "Content-type: text/plainrn";
$mime .= "Content-Transfer-Encoding: base64";
$mime .= "rnrn$attachment_datarn";

mail($to,
    $subject,
    "",
    $mime);
?>

Comments

When sending messages with more than one part, you need a boundary—a unique separator that separates the different parts of the message. Unfortunately, you cannot work with this boundary in the body of a message. Therefore, as in the preceding example, you must specify an empty body and then write out the entire message according to RFC 821.

The message is encoded using base 64 encoding. This isn’t really necessary for text files, but if you want to send binary files, it is vital. The chunk_split() breaks up the blobs into 76 character lines terminated by "rn" in accordance with the RFC 2045 guidelines.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.