1

我已经导出了一个 xls 文件,但我想将此 xls 文件作为邮件的附件邮寄。

导出excel.php

<?php
session_start();


//export format
$fileNamed = $username."_".$date_time; 
header ("Content-type: application/x-msexcel"); 
header ("Content-Disposition: attachment; filename=$fileNamed.xls" ); 
header ("Content-Description: PHP/INTERBASE Generated Data" );

echo $data;
?>

上面的 php 文件在 xls 中导出 $data 中的内容。但我想用附加的 xls 文件邮寄这个 xls 文件。

4

1 回答 1

0

一封电子邮件可以分成许多部分,由一个边界分隔,后跟一个 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);
于 2013-04-09T13:52:57.177 回答