为什么PHP中的邮件发送失败?

4

这是我的代码:

<?php
//define the receiver of the email
$to = 'dannyfeher69@gmail.com';
//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: me@localhost.com";
//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
请将mail()函数前面的@符号移除,并告诉我们是否有任何错误或警告信息显示。 - Jan Hančič
网页被托管在哪里? - user557846
邮件是通过哪个(SMTP)服务器发送的?这个配置好了吗? - Caspar Kleijne
1个回答

12
有几个原因可能导致邮件发送失败。找出原因的主要障碍是在调用mail()函数前使用错误控制运算符(@)。
其他可能的原因是缺少有效的发件人头信息。虽然你在$header变量中定义了一个发件人头信息,但你没有将它传递给mail()函数。另外,发件人头信息必须是当前域上的有效电子邮件地址。如果不是,大多数托管公司现在会将邮件拒绝为垃圾邮件。你可能还需要为mail()提供第五个参数,这通常由一个字符串组成,其中-f后跟当前域上的有效电子邮件地址。
另一个可能性是你正在尝试从自己的计算机发送邮件。mail()函数不支持SMTP身份验证,因此大多数邮件服务器将拒绝来自未知源的邮件。
还有一个问题是,电子邮件中的换行必须是回车符后跟换行符的组合。在PHP中,这是"\r\n",而不是"\n\n"。
假设你正在使用远程服务器发送邮件,则代码应该如下所示:
<?php
//define the receiver of the email
$to = 'dannyfeher69@gmail.com';
//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: me@localhost.com"; // 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";
?>

1
谢谢 :) 我必须配置SMTP。 - Danny Feher

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接