一封电子邮件可以分成许多部分,由一个边界分隔,后跟一个 Content-Type 和一个 Content-Disposition。
边界初始化如下:
<?php
$boundary = '-----=' . md5( uniqid ( rand() ) );
?>
如果您指定,您可以附加 Word 文档:
<?php
$message .= "Content-Type: application/msword; name=\"my attachment\"\n";
$message .= "Content-Transfer-Encoding: base64\n";
$message .= "Content-Disposition: attachment; filename=\"$theFile\"\n\n";
?>
添加文件时,您必须打开它并使用 fopen 读取它并将内容添加到消息中:
<?php
$path = "whatever the path to the file is";
$fp = fopen($path, 'r');
do //we loop until there is no data left
{
$data = fread($fp, 8192);
if (strlen($data) == 0) break;
$content .= $data;
} while (true);
$content_encode = chunk_split(base64_encode($content));
$message .= $content_encode . "\n";
$message .= "--" . $boundary . "\n";
?>
添加所需的标题并发送!
<?php
$headers = "From: \"Me\"<me@example.com>\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"";
mail('myAddress@example.com', 'Email with attachment from PHP', $message, $headers);