如何把php匯出的Excel 作為郵件發送
現在實現了點擊後下載excel,和發送文本郵件的功能,怎麼能結合下,把php匯出的excel作為附件發送就完美了。
1 .產生excel:
header("Content-type:application/octet-stream");
header("Accept-Ranges:bytes");
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:attachment;filename=".$filename.".xls");
header("Pragma: no-cache");
header("Expires: 0");
if (!empty($title)){
foreach ($title as $k => $v) {
$title[$k]=iconv("UTF-8", "GB2312",$v);
}
$title= implode("t", $title);
echo "$titlen";
}
if (!empty($data)){
foreach($data as $key=>$val){
foreach ($val as $ck => $cv) {
$data[$key][$ck]=iconv("UTF-8", "GB2312", $cv);
}
$data[$key]=implode("t", $data[$key]);
}
echo implode("n",$data);
}
2 . 發送郵件:
用了phpmailer類庫
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = '';
$mail->Host = $config['SMTP_HOST']; // SMTP 伺服器
$mail->Port = $config['SMTP_PORT']; // SMTP伺服器的連接埠號碼
$mail->Username = $config['SMTP_USER']; // SMTP伺服器使用者名稱
$mail->Password = $config['SMTP_PASS']; // SMTP伺服器密碼
$mail->SetFrom($config['FROM_EMAIL'], $config['FROM_NAME']);
$replyEmail = $config['REPLY_EMAIL']?$config['REPLY_EMAIL']:$config['FROM_EMAIL'];
$replyName = $config['REPLY_NAME']?$config['REPLY_NAME']:$config['FROM_NAME'];
$mail->AddReplyTo($replyEmail, $replyName);
$mail->Subject = $subject;
$mail->MsgHTML($body);
$mail->AddAddress($to, $name);
if(is_file($attachment)){ // 添加附件
$mail->AddAttachment($attachment);
}
return $mail->Send()
------解決方案--------------------
第7行處加入
ob_start();
第23行後加入
$s = ob_get_flush();
file_put_contents($filename.".xls", $s);
$attachment = $filename.".xls";
執行郵件發送
------解決方案--------------------
肯定是你哪裡出錯了,認真檢查一下
你實際輸出的是文字檔,用記事本就可開啟
ob 函數的功能、用法,手冊中都有
------解決方案--------------------
汗!那樣匯出的還沒有路徑,你如何作為附件發送呢??
你這不是天方夜譚麼?
------解決方案--------------------
提個思路,你可參考下:
先把excel儲存在伺服器上,然後獲得該excel的路徑,然後作為附件進行email發送,如果你不需要這個檔案了,然後再執行刪除操作就OK了