Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
603 views
in Technique[技术] by (71.8m points)

email - Why mail fails in php?

This is my Code :

<?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!

This 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";
?>

-- it returns mail failed

Please help me

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are several reasons this could fail. The main obstacle to finding the cause is the use of the error control operator (@) in front of the call to the mail() function.

Other possible reasons are the lack of a valid From header. Although you define one in the $header variable, you don't pass it to the mail() function. It's also important that the From header is a valid email address on the domain you're sending the email from. If it isn't, most hosting companies will now reject the email as spam. You might also need to supply a fifth parameter to mail(), which normally consists of a string comprised of -f followed by a valid email address on the current domain.

Yet another possibility is that you are trying to send this from your own computer. The mail() function doesn't support SMTP authentication, so most mail servers will reject mail from sources they don't recognize.

And just to add to all your problems, newlines in emails must be a combination of carriage return followed by newline. In PHP, this is " ", not " ".

Assuming you're using a remote server to send the mail, the code should look something like this:

<?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!
This 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";
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...