Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why mail fails in php?

Tags:

php

email

This is my Code :

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

-- it returns mail failed

Please help me

like image 428
Danny Feher Avatar asked Dec 17 '22 18:12

Danny Feher


1 Answers

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 "\r\n", not "\n\n".

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 = '[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";
?>
like image 77
David Powers Avatar answered Jan 04 '23 01:01

David Powers