2012-08-17 68 views
1

我用代碼來發送電子郵件:簡單的腳本發送電子郵件?

<?php 
$to = "[email protected]"; 
$subject = "Test mail"; 
$message = "Hello! This is a simple email message."; 
$from = "[email protected]"; 
$headers = "From:" . $from; 
mail($to,$subject,$message,$headers); 
echo "Mail Sent."; 
?> 

但我得到:

的sendmail:致命的:CHDIR /庫/服務器/郵件/數據/閥芯:沒有這樣的文件或目錄

我不知道如何添加附件,重要的是我需要指定Content-Type的附件,任何人都可以幫助我嗎?

謝謝!

+0

您使用的是Linux還是OSX? – mittmemo 2012-08-17 03:40:36

+2

您的服務器(Mac?)配置錯誤,您必須先解決該問題,然後才能發送郵件。然後使用PHPmailer或Swiftmailer查看電子郵件 - 使用mail()發送附件非常痛苦且容易出錯。 – 2012-08-17 03:46:19

+0

@MarcB它絕對是一個有趣的體驗,處理附件和各種mime組合自己雖然;-) – 2012-08-17 04:04:06

回答

2
<?php 

$to = "[email protected]"; 
$subject = "Test mail"; 
$from = "[email protected] <[email protected]>"; 
$message = "Hello! This is a simple email message."; 

// let's say you want to email a comma-separated-values 
$tofile = "col1,col2,col3\n"; 
$tofile .= "val1,val1,val1\n"; 


$filename = "filename.csv"; 
$random_hash = md5(date('r', time())); 
$attachment = chunk_split(base64_encode($tofile)); 

$headers = "From: " . $from . "\r\n"; 
$headers .= "MIME-Version: 1.0\r\n"; 
$headers .= "Content-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"\r\n"; 
$headers .= "X-Priority: 3\r\n"; 
$headers .= "X-MSMail-Priority: Normal\r\n";  
$headers .= "X-Mailer: PHP/" . phpversion(); 

$body = "--PHP-mixed-".$random_hash."\r\n"; 
$body .= "Content-Type: text/plain; charset=\"UTF-8\"\r\n"; 
$body .= "Content-Transfer-Encoding: 8bit\r\n"; 
$body .= $message; 
$body .= "\r\n\r\n"; 
$body .= "\r\n--PHP-mixed-" . $random_hash . "\r\n\r\n"; 

$body .= "--PHP-mixed-".$random_hash."\r\n"; 
$body .= "Content-Transfer-Encoding: base64\r\n"; 
$body .= "Content-Type: text/comma-separated-values; name=\"" . $filename . "\" charset=\"UTF-8\"\r\n"; 
$body .= "Content-Disposition: attachment; filename=\"" . $filename . "\"\r\n\r\n"; 
$body .= $attachment; 
$body .= "\r\n--PHP-mixed-".$random_hash."--"; 

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

?>