2011-01-08 89 views
3

這是我的代碼:爲什麼郵件在php中失敗?

<?php 
//define the receiver of the email 
$to = '[email protected]'; 
//define the subject of the email 
$subject = 'Test email'; 
//define the message to be sent. 
$message = "Hello World!\n\nThis is my mail."; 
//define the headers we want passed. 
$header = "From: [email protected]"; 
//send the email 
$mail_sent = @mail($to, $subject, $message); 
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" 

echo $mail_sent ? "Mail sent" : "Mail failed"; 
?> 

- 返回郵件失敗

請幫我

+4

刪除`@`的`郵件前()`函數,如果任何告訴我們顯示錯誤/警告。 – 2011-01-08 09:13:13

+0

在哪裏託管的網頁? – 2011-01-08 09:15:26

回答

10

有幾個原因,這可能會失敗。找到原因的主要障礙是在調用mail()函數之前使用錯誤控制運算符(@)。

其他可能的原因是缺少有效的From頭。雖然您在$ header變量中定義了一個變量,但您不會將它傳遞給mail()函數。 From標題是您發送電子郵件的域上的有效電子郵件地址也很重要。如果不是這樣,大多數託管公司現在都會拒絕將電子郵件作爲垃圾郵件。您可能還需要向mail()提供第五個參數,通常由包含-f的字符串組成,後跟當前域上的有效電子郵件地址。

另一種可能性是,您正試圖從您自己的計算機上發送此信息。 mail()函數不支持SMTP驗證,因此大多數郵件服務器將拒絕來自他們無法識別的源的郵件。

爲了增加您的所有問題,電子郵件中的換行符必須是換行符和換行符的組合。在PHP中,這是「\ r \ n」,而不是「\ n \ n」。

假設你正在使用遠程服務器來發送郵件,代碼應該是這個樣子:

<?php 
//define the receiver of the email 
$to = '[email protected]'; 
//define the subject of the email 
$subject = 'Test email'; 
//define the message to be sent. 
$message = "Hello World!\r\nThis is my mail."; 
//define the headers we want passed. 
$header = "From: [email protected]"; // must be a genuine address 
//send the email 
$mail_sent = mail($to, $subject, $message, $header); 
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" 

echo $mail_sent ? "Mail sent" : "Mail failed"; 
?>