为什么邮件在PHP中失败?

Dan*_*her 4 php email

这是我的代码:

<?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";
?>
Run Code Online (Sandbox Code Playgroud)

- 它返回邮件失败

请帮我

Dav*_*ers 12

有几个原因可能会失败.找到原因的主要障碍是在调用mail()函数之前使用错误控制操作符(@).

其他可能的原因是缺少有效的From标头.虽然您在$ header变量中定义了一个,但是不将它传递给mail()函数.From头是您发送电子邮件的域上的有效电子邮件地址也很重要.如果不是,大多数托管公司现在将拒绝该电子邮件作为垃圾邮件.您可能还需要为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";
?>
Run Code Online (Sandbox Code Playgroud)