Can't send a mail with the php function (Hostinger) [duplicate]

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From:';
$to = '';
$subject = 'Customer Inquiry';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
if ($_POST['submit']) {
if (mail ($to, $subject, $body, $from)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
I've tried creating a simple mail form. The form itself is on my index.html page, but submits to a separate "thank you for your submission" page, thankyou.php, where the above php code is embedded.
The code submits perfectly, but never sends an email. please help.
There are a variety of reasons your script appears to not be sending emails. It's difficult to diagnose these things unless there is an obvious syntax error. Without one you need to run through the checklist below to find any potential pitfalls you may be encountering.
Make sure error reporting is enabled and set to report all errors
Error reporting is essential to rooting out bugs in your code and general errors that PHP encounters. Error reporting needs to be enabled to receive these errors. Placing the following code at the top of your PHP files (or in a master configuration file) will enable error reporting.
ini_set('display_errors', 'On');
See this Stack Overflow answer for more details on this.
Make sure the mail() function is called
It may seem silly but a common error is to forget to actually place the mail() function in your code. Make sure it is there and not commented out.
Check the server's mail logs
Your web server should be logging all attempts to send emails through it. The location of these logs will vary (you may need to ask your server administrator where they are located) but they can commonly be found in a user's root directory under logs. Inside will be error messages the server reported, if any, related to your attempts to send emails.
Don't use the error suppression operator
When the error suppression operator # is prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored. There are circumstances where using this operator is necessary but sending mail is not one of them.
If your code contains #mail(...) then you may be hiding important error messages that will help you debug this. Remove the # and see if any errors are reported.
It's only advisable when you check with error_get_last() right afterwards for concrete failures.
Check the mail() return value
The mail() function:
Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise. It is important to note that just because the mail was accepted for delivery, it does NOT mean the mail will actually reach the intended destination.
This is important to note because:
If you receive a FALSE return value you know the error lies with your server accepting your mail. This probably isn't a coding issue but a server configuration issue. You need to speak to your system administrator to find out why this is happening.
If your receive a TRUE return value it does not mean your email will definitely be sent. It just means the email was sent to its respective handler on the server successfully by PHP. There are still more points of failure outside of PHP's control that can cause the email to not be sent.
So FALSE will help point you in the right direction whereas TRUE does not necessarily mean your email was sent successfully. This is important to note!
Check spam folders; prevent emails from being flagged as spam
Oftentimes, for various reasons, emails sent through PHP (and other server-side programming languages) end up in a recipient's spam folder. Always check there before troubleshooting your code.
To avoid mail sent through PHP from being sent to a recipient's spam folder, there are various things you can do, both in your PHP code and otherwise, to minimize the chances your emails are marked as spam. Good tips from Michiel de Mare include:
Use email authentication methods, such as SPF, and DKIM to prove that your emails and your domain name belong together, and to prevent spoofing of your domain name. The SPF website includes a wizard to generate the DNS information for your site.
Check your reverse DNS to make sure the IP address of your mail server points to the domain name that you use for sending mail.
Make sure that the IP-address that you're using is not on a blacklist
Make sure that the reply-to address is a valid, existing address.
Use the full, real name of the addressee in the To field, not just the email-address (e.g. "John Smith" <> ).
Monitor your abuse accounts, such as and That means - make sure that these accounts exist, read what's sent to them, and act on complaints.
Finally, make it really easy to unsubscribe. Otherwise, your users will unsubscribe by pressing the spam button, and that will affect your reputation.
See How do you make sure email you send programmatically is not automatically marked as spam? for more on this topic.
Make sure all mail headers are supplied
Some spam software will reject mail if it is missing common headers such as "From" and "Reply-to":
$headers = array("From:",
"X-Mailer: PHP/" . PHP_VERSION
$headers = implode("\r\n", $headers);
mail($to, $subject, $message, $headers);
Make sure mail headers have no syntax errors
Invalid headers are just as bad as having no headers. One incorrect character could be all it takes to derail your email. Double-check to make sure your syntax is correct as PHP will not catch these errors for you.
$headers = array("From", // missing colon
"Reply To:", // missing hyphen
"X-Mailer: "PHP"/" . PHP_VERSION // bad quotes
Make sure the recipient value is correct
Sometimes the problem is as simple as having an incorrect value for the recipient of the email. This can be due to using an incorrect variable.
$to = '';
// other variables ....
mail($recipient, $subject, $message, $headers); // $recipient should be $to
Another way to test this is to hard code the recipient value into the mail() function call:
mail('', $subject, $message, $headers);
This can apply to all of the mail() parameters.
Send to multiple accounts
To help rule out email account issues, send your email to multiple email accounts at different email providers. If your emails are not arriving at a user's Gmail account, send the same emails to a Yahoo account, a Hotmail account, and a regular POP3 account (like your ISP-provided email account).
If the emails arrive at all or some of the other email accounts, you know your code is sending emails but it is likely that the email account provider is blocking them for some reason. If the email does not arrive at any email account, the problem is more likely to be related to your code.
Make sure the code matches the form method
If you have set your form method to POST, make sure you are using $_POST to look for your form values. If you have set it to GET or didn't set it at all, make sure you using $_GET to look for your form values.
Make sure the Web host supports sending email
Some Web hosting providers do not allow or enable the sending of emails through their servers. The reasons for this may vary but if they have disabled the sending of mail you will need to use an alternative method that uses a third party to send those emails for you.
An email to their technical support (after a trip to their online support or FAQ) should clarify if email capabilities are available on your server.
Make sure the localhost mail server is configured
If you are developing on your local workstation using WAMP, MAMP, or XAMPP, an email server is probably not installed on your workstation. Without one, PHP cannot send mail by default.
You can overcome this by installing a basic mail server. For Windows you can use the free Mercury Mail.
You can also use SMTP to send your emails. See this great answer from Vikas Dwivedi to learn how to do this.
Enable PHP's custom mail.log
In addition to your MTA's and PHP's log file, you can enable logging for the mail() function specifically. It doesn't record the complete SMTP interaction, but at least function call parameters and invocation script.
ini_set("mail.log", "/tmp/mail.log");
ini_set("mail.add_x_header", TRUE);
See for details. (It's best to enable these options in the php.ini or .user.ini or .htaccess perhaps.)
Use a different mailer
PHP's built in mail() function is handy and often gets the job done but it has its shortcomings. Fortunately there are alternatives that offer more power and flexibility including handling a lot of the issues outlined above. One that would might consider using is the popular PHPMailer or SwiftMailer, or even the older PEAR::Mail.
See Stack Overflow Documentation:
Sending Email - The basics, more details, and a full example
Sending Email with PHPMailer
Add mail header in mail function
$header = "From:\r\n";
$header.= "MIME-Version: 1.0\r\n";
$header.= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$header.= "X-Priority: 1\r\n";
$status = mail($to, $subject, $message, $header);
echo '<p>Your mail has been sent!</p>';
} else {
echo '<p>Something went wrong, Please try again!</p>';
Always try sending headers in mail function.
If you are sending mail through localhost then do the smtp settings for sending mail.
If you are sending mail through server then check the email sending feature is enabled on your server.
are you using SMTP configuration for sending your email?
try using phpmailer instead. you can download the library from i created my email sending this way:
function send_mail($email, $recipient_name, $message='')
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = ""; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "myusername"; // SMTP username
$mail->Password = "p#ssw0rd"; // SMTP password
$mail->From = "";
$mail->FromName = "System-Ad";
$mail->AddAddress($email, $recipient_name);
$mail->WordWrap = 50; // set word wrap to 50 characters
$mail->IsHTML(true); // set email format to HTML (true) or plain text (false)
$mail->Subject = "This is a Sampleenter code here Email";
$mail->Body = $message;
$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
$mail->AddEmbeddedImage('images/logo.png', 'logo', 'logo.png');
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
echo "Message has been sent";
it worked for me on 000webhost by doing the following :
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers .= "From: ". $from. "\r\n";
$headers .= "Reply-To: ". $from. "\r\n";
$headers .= "X-Mailer: PHP/" . phpversion();
$headers .= "X-Priority: 1" . "\r\n";
Enter directly the email address when sending the email
mail('', $subject, $message, $headers)
Use '' and not ""
This code works but the email was received with half an hour lag
Just add some headers before sending mail:
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From:';
$to = '';
$subject = 'Customer Inquiry';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html\r\n";
$headers .= 'From:' . "\r\n" .
'Reply-To:' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
And one more thing. The mail() function is not working in localhost. Upload your code to a server and try.
Try these two thigs separately and together:
remove the if($_POST['submit']){}
remove $from (just my gut)
If you only use the mail()function, you need to complete the config file.
You need to open the mail expansion, and set the SMTP smtp_port and so on, and most important, your username and your password. Without that, mail cannot be sent. Also, you can use PHPMail class to send.
You can use config email by codeigniter, example using smtp (simple way) :
$config = Array(
'protocol' => 'smtp',
'smtp_host' => '', //your smtp host
'smtp_port' => 26, //default port smtp
'smtp_user' => '',
'smtp_pass' => 'password',
'mailtype' => 'html',
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
$message = 'Your msg';
$this->load->library('email', $config);
$this->email->from('', 'Title');
//conditional true
It's works for me!
I think this should do the trick. I just added an if(isset and added concatenation to the variables in the body to separate PHP from HTML.
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From:';
$to = '';
$subject = 'Customer Inquiry';
$body = "From:" .$name."\r\n E-Mail:" .$email."\r\n Message:\r\n" .$message;
if (isset($_POST['submit']))
if (mail ($to, $subject, $body, $from))
echo '<p>Your message has been sent!</p>';
echo '<p>Something went wrong, go back and try again!</p>';
Mostly the mail() function is disabled in shared hosting.
A better option is to use SMTP. The best option would be Gmail or SendGrid.
$SmtpPort="2525"; //default
class SMTPClient
function SMTPClient ($SmtpServer, $SmtpPort, $SmtpUser, $SmtpPass, $from, $to, $subject, $body)
$this->SmtpServer = $SmtpServer;
$this->SmtpUser = base64_encode ($SmtpUser);
$this->SmtpPass = base64_encode ($SmtpPass);
$this->from = $from;
$this->to = $to;
$this->subject = $subject;
$this->body = $body;
if ($SmtpPort == "")
$this->PortSMTP = 25;
$this->PortSMTP = $SmtpPort;
function SendMail ()
$newLine = "\r\n";
$headers = "MIME-Version: 1.0" . $newLine;
$headers .= "Content-type: text/html; charset=iso-8859-1" . $newLine;
if ($SMTPIN = fsockopen ($this->SmtpServer, $this->PortSMTP))
fputs ($SMTPIN, "EHLO ".$HTTP_HOST."\r\n");
$talk["hello"] = fgets ( $SMTPIN, 1024 );
fputs($SMTPIN, "auth login\r\n");
fputs($SMTPIN, $this->SmtpUser."\r\n");
fputs($SMTPIN, $this->SmtpPass."\r\n");
fputs ($SMTPIN, "MAIL FROM: <".$this->from.">\r\n");
$talk["From"] = fgets ( $SMTPIN, 1024 );
fputs ($SMTPIN, "RCPT TO: <".$this->to.">\r\n");
$talk["To"] = fgets ($SMTPIN, 1024);
fputs($SMTPIN, "DATA\r\n");
$talk["data"]=fgets( $SMTPIN,1024 );
fputs($SMTPIN, "To: <".$this->to.">\r\nFrom: <".$this->from.">\r\n".$headers."\n\nSubject:".$this->subject."\r\n\r\n\r\n".$this->body."\r\n.\r\n");
fputs ($SMTPIN, "QUIT\r\n");
return $talk;
$to = "";
$from = $_POST['email'];
$subject = "Enquiry";
$body = $_POST['name'].'</br>'.$_POST['companyName'].'</br>'.$_POST['tel'].'</br>'.'<hr />'.$_POST['message'];
$SMTPMail = new SMTPClient ($SmtpServer, $SmtpPort, $SmtpUser, $SmtpPass, $from, $to, $subject, $body);
$SMTPChat = $SMTPMail->SendMail();
$name = $_POST['name'];
$email = $_POST['email'];
$reciver = '/* Reciver Email address */';
if (filter_var($reciver, FILTER_VALIDATE_EMAIL)) {
$subject = $name;
// To send HTML mail, the Content-type header must be set.
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From:' . $email. "\r\n"; // Sender's Email
//$headers .= 'Cc:' . $email. "\r\n"; // Carbon copy to Sender
$template = '<div style="padding:50px; color:white;">Hello ,<br/>'
. '<br/><br/>'
. 'Name:' .$name.'<br/>'
. 'Email:' .$email.'<br/>'
. '<br/>'
. '</div>';
$sendmessage = "<div style=\"background-color:#7E7E7E; color:white;\">" . $template . "</div>";
// Message lines should not exceed 70 characters (PHP rule), so wrap it.
$sendmessage = wordwrap($sendmessage, 70);
// Send mail by PHP Mail Function.
mail($reciver, $subject, $sendmessage, $headers);
echo "Your Query has been received, We will contact you soon.";
} else {
echo "<span>* invalid email *</span>";
For anyone who finds this going forward, I would not recommend using mail. There's some answers that touch on this, but not the why of it.
PHP's mail function is not only opaque, it fully relies on whatever MTA you use (i.e. Sendmail) to do the work. mail will ONLY tell you if the MTA failed to accept it (i.e. Sendmail was down when you tried to send). It cannot tell you if the mail was successful because it's handed it off. As such (as John Conde's answer details), you now get to fiddle with the logs of the MTA and hope that it tells you enough about the failure to fix it. If you're on a shared host or don't have access to the MTA logs, you're out of luck. Sadly, the default for most vanilla installs for Linux handle it this way.
A mail library (PHPMailer, Zend Framework 2+, etc), does something very different from mail. What they do is they open a socket directly to the receiving mail server and then send the SMTP mail commands directly over that socket. In other words, the class acts as its own MTA (note that you can tell the libraries to use mail to ultimately send the mail, but I would strongly recommend you not do that).
What this means for you is that you can then directly see the responses from the receiving server (in PHPMailer, for instance, you can turn on debugging output). No more guessing if a mail failed to send or why.
If you're using SMTP (i.e. you're calling isSMTP()), you can get a detailed transcript of the SMTP conversation using the SMTPDebug property.
Set this option by including a line like this in your script:
$mail->SMTPDebug = 2;
You also get the benefit of a better interface. With mail you have to set up all your headers, attachments, etc. With a library, you have a dedicated function to do that. It also means the function is doing all the tricky parts (like headers).
Try this
$to = ",";
$subject = "HTML email";
$message = "
<title>HTML email</title>
<p>This email contains HTML Tags!</p>
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers
$headers .= 'From: <>' . "\r\n";
$headers .= 'Cc:' . "\r\n";
Try this
if ($_POST['submit']) {
$success= mail($to, $subject, $body, $from);
echo '
<p>Your message has been sent!</p>
} else {
echo '
<p>Something went wrong, go back and try again!</p>
If you're having trouble sending mails with PHP, consider an alternative like PHPMailer or SwiftMailer.
I usually use SwiftMailer whenever I need to send mails with PHP.
Basic usage :
require 'mail/swift_required.php';
$message = Swift_Message::newInstance()
// The subject of your email
->setSubject('Jane Doe sends you a message')
// The from address(es)
->setFrom(array('' => 'Jane Doe'))
// The to address(es)
->setTo(array('' => 'Frank Stevens'))
// Here, you put the content of your email
->setBody('<h3>New message</h3><p>Here goes the rest of my message</p>', 'text/html');
if (Swift_Mailer::newInstance(Swift_MailTransport::newInstance())->send($message)) {
echo json_encode([
"status" => "OK",
"message" => 'Your message has been sent!'
} else {
echo json_encode([
"status" => "error",
"message" => 'Oops! Something went wrong!'
See the official documentation for more info on how to use SwiftMailer.
You can use empty() and isset() functions. If you want to make it work with different files, just modify the action='yourphp.php' to the html I'm giving you, and store the PHP script to that yourphp.php file. Also you need to change your index.html into index.php to activate PHP functionality.
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From:';
$to = '';
$subject = 'Customer Inquiry';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
if ($_POST['submit']){
if (!(empty($_POST['name']))) {
if (!(empty($_POST['email']))){
if (!(empty($_POST['message']))){
mail ($to, $subject, $body, $from);
echo '<p>Your message has been sent!</p>';
echo '<p>Fill your message please.</p>';}
}else {
echo '<p>Fill your email please.</p>';}
echo '<p>Fill your name please.</p>';}
echo '<p>Fill the form.</p>';}
<form method="post" action="?">
<tr><td>Name</td><td><input type='text' name='name' id='name'/></td></tr>
<tr><td>Email</td><td><input type='text' name='email' id='email'/></td></tr>
<tr><td>Message</td><td><input type='text' name='message' id='message'/></td></tr>
<tr><td></td><td><input type='submit' name='submit' id='submit'/></td></tr>
Best Regards!
First of all,
You might have to many parameters for the mail() function...
You are able to have 5 max. mail(to,subject,message,headers,parameters);
As far as the $from variable goes, that should automatically come from your webhost if your using linux cPanel. It automatically comes from your cPanel username and ip address.
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From:';
$to = '';
$subject = 'Customer Inquiry';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
Also make sure you have the correct order of variables in your mail() function.
the mail($to,$subject,$message,etc.) in that order, or else there is a chance of it not working.
Let me know if this helps...
If you are running this code on a local server (i.e your computer for development purposes) it wont send the email to the recipient. What will happen is, it will create a .txt file in a folder named mailoutput.
In the case if you are using a free hosing service like 000webhost or hostinger, those service providers disable the mail() function to prevent unintended uses of email spoofing, spamming etc. I prefer you to contact them to see whether they support this feature.
If you are sure that the service provider supports the mail() function, you can check this PHP manual for further reference,
PHP mail()
To check weather your hosting service support the mail() function, try running this code, (Remember to change the recipient email address)
$to = '';
$subject = 'the subject';
$message = 'hello';
$headers = 'From:' . "\r\n" .
'Reply-To:' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
Hope this helped.
This will only affect a small handful of users, but I'd like it documented for that small handful. This member of that small handful spent 6 hours troubleshooting a working PHP mail script because of this issue.
If you're going to a university that runs XAMPP from, you should know what our professor didn't tell us: The AceITLab firewall (not the Windows firewall) blocks MercuryMail in XAMPP. You'll have to use an alternative mail client, pear is working for us. You'll have to send to a Gmail account with low security settings.
Yes, I know, this is totally useless for real world email. However, from what I've seen, academic settings and the real world often have precious little in common.
convert every $_POST['$myVar']; before u sending it to String using php function .
You can use the casting operators:
$myText = (string)$myVar;
There are more details for string casting and conversion in the Strings section of the PHP manual, including special handling for booleans and nulls.
or here:(convert-variable-string-php)

Related Links

Distant SQL connexion with CodeIgniter
Multiple inputs with same name and different name
PHP - Rewrite foreach loop as a for loop to have a counter
Why is pHp giving me this error?
How to check if the file is flash or image file in PHP?
Foursquare - Less venue response results when using the endpoints 'venues/explore' than 'venues/search'
I get an error: Property “CListView.afterAjaxUpdate ” is not defined. when using afterAjaxUpdate in clistview in yii
dependancy injection in laravel controller
Cannot connect to MySQL server on Openshift
css for dynamic rows not working
how to manage json data in php
headers get sent even after output in php (laravel)
Displaying Searched Terms On Results Page Issue
Symfony - Form validation error about something is blank although all fields are entered
User Authentication Across Subdomains on Localhost
add ' to front of string from vector




Mobile Apps Dev
Database Users
MS Developer
developer works
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
Mobile App
Mobile App
Mobile App