html - PHP mail function doesn't complete sending of e-mail

4

Solution:

Although there are portions of this answer that apply to only to the usage of themail() function itself, many of these troubleshooting steps can be applied to any PHP mailing system.

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.

error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");

See How can I get useful error messages in PHP?this answer for more details on this.

Make sure themail() function is called

It may seem silly but a common error is to forget to actually place themail() function in your code. Make sure it is there and not commented out.

Make sure themail() function is called correctly

bool mail ( string $to, string $subject, string $message [, string $additional_headers [, string $additional_parameters ]] )

The mail function takes three required parameters and optionally a fourth and fifth one. If your call tomail() does not have at least three parameters it will fail.

If your call tomail() does not have the correct parameters in the correct order it will also fail.

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 underlogs. Inside will be error messages the server reported, if any, related to your attempts to send emails.

Check for Port connection failure

Port block is a very common problem which most developers face while integrating their code to deliver emails using SMTP. And, this can be easily traced at the server maillogs (the location of server of mail log can vary from server to server, as explained above). In case you are on a shared hosting server, the ports 25 and 587 remain blocked by default. This block is been purposely done by your hosting provider. This is true even for some of the dedicated servers. When these ports are blocked, try to connect using port 2525. If you find that port is also blocked, then the only solution is to contact your hosting provider to unblock these ports.

Most of the hosting providers block these email ports to protect their network from sending any spam emails.

Use ports 25 or 587 for plain/TLS connections and port 465 for SSL connections. For most users, it is suggested to use port 587 to avoid rate limits set by some hosting providers.

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 right afterwards for concrete failures.

Check themail() return value

The function:

ReturnsTRUE 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 aFALSE 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 you receive aTRUE 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.

SoFALSE will help point you in the right direction whereasTRUE does not necessarily mean your email was sent successfully. This is important to note!

Make sure your hosting provider allows you to send emails and does not limit mail sending

Many shared webhosts, especially free webhosting providers, either do not allow emails to be sent from their servers or limit the amount that can be sent during any given time period. This is due to their efforts to limit spammers from taking advantage of their cheaper services.

If you think your host has emailing limits or blocks the sending of emails, check their FAQs to see if they list any such limitations. Otherwise, you may need to reach out to their support to verify if there are any restrictions in place around the sending of emails.

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" <[email protected]> ).
  • Monitor your abuse accounts, such as[email protected] and[email protected]. 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: [email protected]",
    "Reply-To: [email protected]",
    "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 [email protected]", // missing colon
    "Reply To: [email protected]",      // missing hyphen
    "X-Mailer: "PHP"/" . PHP_VERSION      // bad quotes
);

Don't use a fauxFrom: sender

While the mail must have a From: sender, you may not just use any value. In particular user-supplied sender addresses are a surefire way to get mails blocked:

$headers = array("From: $_POST[contactform_sender_email]"); // No!

Reason: your web or sending mail server is not SPF/DKIM-whitelisted to pretend being responsible for @hotmail or @gmail addresses. It may even silently drop mails withFrom: sender domains it's not configured for.

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 = '[email protected]';
// other variables ....
mail($recipient, $subject, $message, $headers); // $recipient should be $to

Another way to test this is to hard code the recipient value into themail() function call:

mail('[email protected]', $subject, $message, $headers);

This can apply to all of themail() 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 toPOST, make sure you are using$_POST to look for your form values. If you have set it toGET or didn't set it at all, make sure you use$_GET to look for your form values.

Make sure your formaction value points to the correct location

Make sure your formaction attribute contains a value that points to your PHP mailing code.

<form action="send_email.php" method="POST">

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 thelocalhost 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 custommail.log

In addition to your MTA's and PHP's log file, you can enable logging for the 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 http://php.net/manual/en/mail.configuration.php for details. (It's best to enable these options in thephp.ini or.user.ini or.htaccess perhaps.)

Check with a mail testing service

There are various delivery and spamminess checking services you can utilize to test your MTA/webserver setup. Typically you send a mail probe To: their address, then get a delivery report and more concrete failures or analyzations later:

Use a different mailer

PHP's built-inmail() 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:

All of which can be combined with a professional SMTP server/service provider. (Because typical 08/15 shared webhosting plans are hit or miss when it comes to email setup/configurability.)

240

Answer

Solution:

Although there are portions of this answer that apply to only to the usage of themail() function itself, many of these troubleshooting steps can be applied to any PHP mailing system.

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.

error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");

See How can I get useful error messages in PHP?this answer for more details on this.

Make sure themail() function is called

It may seem silly but a common error is to forget to actually place themail() function in your code. Make sure it is there and not commented out.

Make sure themail() function is called correctly

bool mail ( string $to, string $subject, string $message [, string $additional_headers [, string $additional_parameters ]] )

The mail function takes three required parameters and optionally a fourth and fifth one. If your call tomail() does not have at least three parameters it will fail.

If your call tomail() does not have the correct parameters in the correct order it will also fail.

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 underlogs. Inside will be error messages the server reported, if any, related to your attempts to send emails.

Check for Port connection failure

Port block is a very common problem which most developers face while integrating their code to deliver emails using SMTP. And, this can be easily traced at the server maillogs (the location of server of mail log can vary from server to server, as explained above). In case you are on a shared hosting server, the ports 25 and 587 remain blocked by default. This block is been purposely done by your hosting provider. This is true even for some of the dedicated servers. When these ports are blocked, try to connect using port 2525. If you find that port is also blocked, then the only solution is to contact your hosting provider to unblock these ports.

Most of the hosting providers block these email ports to protect their network from sending any spam emails.

Use ports 25 or 587 for plain/TLS connections and port 465 for SSL connections. For most users, it is suggested to use port 587 to avoid rate limits set by some hosting providers.

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 right afterwards for concrete failures.

Check themail() return value

The function:

ReturnsTRUE 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 aFALSE 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 you receive aTRUE 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.

SoFALSE will help point you in the right direction whereasTRUE does not necessarily mean your email was sent successfully. This is important to note!

Make sure your hosting provider allows you to send emails and does not limit mail sending

Many shared webhosts, especially free webhosting providers, either do not allow emails to be sent from their servers or limit the amount that can be sent during any given time period. This is due to their efforts to limit spammers from taking advantage of their cheaper services.

If you think your host has emailing limits or blocks the sending of emails, check their FAQs to see if they list any such limitations. Otherwise, you may need to reach out to their support to verify if there are any restrictions in place around the sending of emails.

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" <[email protected]> ).
  • Monitor your abuse accounts, such as[email protected] and[email protected]. 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: [email protected]",
    "Reply-To: [email protected]",
    "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 [email protected]", // missing colon
    "Reply To: [email protected]",      // missing hyphen
    "X-Mailer: "PHP"/" . PHP_VERSION      // bad quotes
);

Don't use a fauxFrom: sender

While the mail must have a From: sender, you may not just use any value. In particular user-supplied sender addresses are a surefire way to get mails blocked:

$headers = array("From: $_POST[contactform_sender_email]"); // No!

Reason: your web or sending mail server is not SPF/DKIM-whitelisted to pretend being responsible for @hotmail or @gmail addresses. It may even silently drop mails withFrom: sender domains it's not configured for.

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 = '[email protected]';
// other variables ....
mail($recipient, $subject, $message, $headers); // $recipient should be $to

Another way to test this is to hard code the recipient value into themail() function call:

mail('[email protected]', $subject, $message, $headers);

This can apply to all of themail() 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 toPOST, make sure you are using$_POST to look for your form values. If you have set it toGET or didn't set it at all, make sure you use$_GET to look for your form values.

Make sure your formaction value points to the correct location

Make sure your formaction attribute contains a value that points to your PHP mailing code.

<form action="send_email.php" method="POST">

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 thelocalhost 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 custommail.log

In addition to your MTA's and PHP's log file, you can enable logging for the 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 http://php.net/manual/en/mail.configuration.php for details. (It's best to enable these options in thephp.ini or.user.ini or.htaccess perhaps.)

Check with a mail testing service

There are various delivery and spamminess checking services you can utilize to test your MTA/webserver setup. Typically you send a mail probe To: their address, then get a delivery report and more concrete failures or analyzations later:

Use a different mailer

PHP's built-inmail() 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:

All of which can be combined with a professional SMTP server/service provider. (Because typical 08/15 shared webhosting plans are hit or miss when it comes to email setup/configurability.)

891

Answer

Solution:

Add a mail header in the mail function:

$header = "From: [email protected]\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);

if($status)
{
    echo '<p>Your mail has been sent!</p>';
} else {
    echo '<p>Something went wrong. Please try again!</p>';
}
699

Answer

Solution:

  1. Always try sending headers in the mail function.
  2. If you are sending mail through localhost then do the SMTP settings for sending mail.
  3. If you are sending mail through a server then check the email sending feature is enabled on your server.
510

Answer

Solution:

If you are using an SMTP configuration for sending your email, try using PHPMailer instead. You can download the library from https://github.com/PHPMailer/PHPMailer.

I created my email sending this way:

function send_mail($email, $recipient_name, $message='')
{
    require("phpmailer/class.phpmailer.php");

    $mail = new PHPMailer();

    $mail->CharSet = "utf-8";
    $mail->IsSMTP();                                      // Set mailer to use SMTP
    $mail->Host = "mail.example.com";  // Specify main and backup server
    $mail->SMTPAuth = true;     // Turn on SMTP authentication
    $mail->Username = "myusername";  // SMTP username
    $mail->Password = "[email protected]"; // SMTP password

    $mail->From = "[email protected]";
    $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');
    $mail->addAttachment('files/file.xlsx');

    if(!$mail->Send())
    {
       echo "Message could not be sent. <p>";
       echo "Mailer Error: " . $mail->ErrorInfo;
       exit;
    }

    echo "Message has been sent";
}
535

Answer

Solution:

Just add some headers before sending mail:

<?php 
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com'; 
$to = '[email protected]'; 
$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: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

And one more thing. Themail() function is not working in localhost. Upload your code to a server and try.

99

Answer

Solution:

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('[email protected]', $subject, $message, $headers)

Use'' and not"".

This code works, but the email was received with half an hour lag.

692

Answer

Solution:

Mostly themail() function is disabled in shared hosting. A better option is to use SMTP. The best option would be Gmail or SendGrid.


SMTPconfig.php

<?php 
    $SmtpServer="smtp.*.*";
    $SmtpPort="2525"; //default
    $SmtpUser="***";
    $SmtpPass="***";
?>

SMTPmail.php

<?php
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;
        }
        else
        {
            $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");
            $talk["res"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpUser."\r\n");
            $talk["user"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpPass."\r\n");
            $talk["pass"]=fgets($SMTPIN,256);
            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");
            $talk["send"]=fgets($SMTPIN,256);
            //CLOSE CONNECTION AND EXIT ... 
            fputs ($SMTPIN, "QUIT\r\n"); 
            fclose($SMTPIN); 
            // 
        } 
        return $talk;
    } 
}
?>

contact_email.php

<?php 
include('SMTPconfig.php');
include('SMTPmail.php');
if($_SERVER["REQUEST_METHOD"] == "POST")
{
    $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();
}
?>
766

Answer

Solution:

If you only use themail()function, you need to complete the configuration file.

You need to open the mail expansion, and set theSMTP smtp_port and so on, and most important, your username and your password. Without that, mail cannot be sent. Also, you can use thePHPMail class to send.

584

Answer

Solution:

Try these two things separately and together:

  1. remove theif($_POST['submit']){}
  2. remove$from (just my gut)
888

Answer

Solution:

I think this should do the trick. I just added anif(isset and added concatenation to the variables in the body to separate PHP from HTML.

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: yoursite.com'; 
    $to = '[email protected]'; 
    $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>';
    } 
    else 
    { 
        echo '<p>Something went wrong, go back and try again!</p>'; 
    }
}

?>
968

Answer

Solution:

For anyone who finds this going forward, I would not recommend usingmail. There's some answers that touch on this, but not the why of it.

PHP'smail 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 frommail. 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 usemail to ultimately send the mail, but I would strongly recommend you not do that).

This means 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 callingisSMTP()), you can get a detailed transcript of the SMTP conversation using theSMTPDebug 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. Withmail 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).

472

Answer

Solution:

$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 class="page_speed_1833695416">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>";
}
408

Answer

Solution:

You can use config email by CodeIgniter. For example, using SMTP (simple way):

$config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'mail.domain.com', // Your SMTP host
        'smtp_port' => 26, // Default port for SMTP
        'smtp_user' => '[email protected]',
        'smtp_pass' => 'password',
        'mailtype' => 'html',
        'charset' => 'iso-8859-1',
        'wordwrap' => TRUE
);
$message = 'Your msg';
$this->load->library('email', $config);
$this->email->from('[email protected]', 'Title');
$this->email->to('[email protected]');
$this->email->subject('Header');
$this->email->message($message);

if($this->email->send()) 
{
   // Conditional true
}

It works for me!

139

Answer

Solution:

Try this

if ($_POST['submit']) {
    $success= mail($to, $subject, $body, $from);
    if($success)
    { 
        echo '
        <p>Your message has been sent!</p>
        ';
    } else { 
        echo '
        <p>Something went wrong, go back and try again!</p>
        '; 
    }
}
549

Answer

Solution:

Maybe the problem is the configuration of the mail server. To avoid this type of problems or you do not have to worry about the mail server problem, I recommend you use PHPMailer.

It is a plugin that has everything necessary to send mail, and the only thing you have to take into account is to have the SMTP port (Port: 25 and 465), enabled.

require_once 'PHPMailer/PHPMailer.php';
require_once '/servicios/PHPMailer/SMTP.php';
require_once '/servicios/PHPMailer/Exception.php';

$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
    //Server settings
    $mail->SMTPDebug = 0;
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = '[email protected]';
    $mail->Password = 'contrasenia';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;

    // Recipients
    $mail->setFrom('[email protected]', 'my name');
    $mail->addAddress('[email protected]');

    // Attachments
    $mail->addAttachment('optional file');         // Add files, is optional

    // Content
    $mail->isHTML(true);// Set email format to HTML
    $mail->Subject = utf8_decode("subject");
    $mail->Body    = utf8_decode("mail content");
    $mail->AltBody = '';
    $mail->send();
}
catch (Exception $e) {
    $error = $mail->ErrorInfo;
}
725

Answer

Solution:

First of all, you might have too many parameters for the mail() function... You are able to have of maximum of five,mail(to, subject, message, headers, parameters);

As far as the$from variable goes, that should automatically come from your webhost if your using the Linux cPanel. It automatically comes from your cPanel username and IP address.

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com';
$to = '[email protected]';
$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.

Themail($to, $subject, $message, etc.) in that order, or else there is a chance of it not working.

960

Answer

Solution:

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 www.AceITLab.com, 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.

12

Answer

Solution:

Make sure you have Sendmail installed in your server.

If you have checked your code and verified that there is nothing wrong there, go to /var/mail and check whether that folder is empty.

If it is empty, you will need to do a:

sudo apt-get install sendmail

if you are on an Ubuntu server.

396

Answer

Solution:

For those who do not want to use external mailers and want to mail() on a dedicated Linux server.

The way, how PHP mails, is described inphp.ini in section[mail function].

Parametersendmail-path describes how sendmail is called. The default value issendmail -t -i, so if you get a workingsendmail -t -i < message.txt in the Linux console - you will be done. You could also addmail.log to debug and be sure mail() is really called.

Different MTAs can implementsendmail. They just make a symbolic link to their binaries on that name. For example, in Debian the default is Postfix. Configure your MTA to send mail and test it from the console withsendmail -v -t -i < message.txt. Filemessage.txt should contain all headers of a message and a body, destination address for the envelope will be taken from theTo: header. Example:

From: [email protected]
To: [email protected]
Subject: Test mail via sendmail.

Text body.

I prefer to use ssmtp as MTA because it is simple and does not require running a daemon with opened ports. ssmtp fits only for sending mail from localhost. It also can send authenticated email via your account on a public mail service. Install ssmtp and edit configuration file/etc/ssmtp/ssmtp.conf. To be able also to receive local system mail to Unix accounts (alerts to root from cron jobs, for example) configure/etc/ssmtp/revaliases file.

Here is my configuration for my account on Yandex mail:

[email protected]
mailhub=smtp.yandex.ru:465
FromLineOverride=YES
UseTLS=YES
[email protected]
AuthPass=password
734

Answer

Solution:

Sendmail installation for Debian 10.0.0 ('Buster') was in fact trivial!

php.ini

[mail function]
sendmail_path=/usr/sbin/sendmail -t -i
; (Other directives are mostly windows)

Standard sendmail package install (allowing 'send'):

su -                                        # Install as user 'root'
dpkg --list                                 # Is install necessary?
apt-get install sendmail sendmail-cf m4     # Note multiple package selection
sendmailconfig                              # Respond all 'Y' for new install

Miscellaneous useful commands:

which sendmail                              # /usr/sbin/sendmail
which sendmailconfig                        # /usr/sbin/sendmailconfig
man sendmail                                # Documentation
systemctl restart sendmail                  # As and when required

Verification (of ability to send)

echo "Subject: sendmail test" | sendmail -v <yourEmail>@gmail.com

The above took about 5 minutes. Then I wasted 5 hours... Don't forget to check your spam folder!

424

Answer

Solution:

If you are running this code on a local server (i.e your computer for development purposes) it won't send the email to the recipient. It will create a.txt file in a folder namedmailoutput.

In the case if you are using a free hosing service, like000webhost orhostinger, those service providers disable themail() 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):

<?php
    $to      = '[email protected]';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: [email protected]' . "\r\n" .
        'Reply-To: [email protected]' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
?>
835

Answer

Solution:

You can use thePHPMailer and it works perfectly,here's a code example:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/phpmailer/phpmailer/src/Exception.php';
require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/phpmailer/src/SMTP.php';
$editor = $_POST["editor"];
$subject = $_POST["subject"];
$to = $_POST["to"];

try {

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->Mailer = "smtp";
        $mail->SMTPDebug  = 1;
        $mail->SMTPAuth   = TRUE;
        $mail->SMTPSecure = "tls";
        $mail->Port       = 587;
        $mail->Host       = "smtp.gmail.com";//using smtp server
        $mail->Username   = "[email protected]";//the email which will send the email 
        $mail->Password   = "XXXXXXXXXX";//the password

        $mail->IsHTML(true);
        $mail->AddAddress($to, "recipient-name");
        $mail->SetFrom("[email protected]", "from-name");
        $mail->AddReplyTo("[email protected]", "reply-to-name");
        $mail->Subject = $subject;
        $mail->MsgHTML($editor);




        if (!$mail->Send()) {
            echo "Error while sending Email.";
            var_dump($mail);
        } else {
            echo "Email sent successfully";
        }
    }
} catch (Exception $e) {
    echo $e->getMessage();
}
859

Answer

Solution:

You can see your errors by:

error_reporting(E_ALL);

And my sample code is:

<?php
    use PHPMailer\PHPMailer\PHPMailer;
    require 'PHPMailer.php';
    require 'SMTP.php';
    require 'Exception.php';

    $name = $_POST['name'];
    $mailid = $_POST['mail'];
    $mail = new PHPMailer;
    $mail->IsSMTP();
    $mail->SMTPDebug = 0;                   // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';         // Specify main and backup server
    $mail->Port = 587;                      // Set the SMTP port
    $mail->SMTPAuth = true;                 // Enable SMTP authentication
    $mail->Username = '[email protected]';  // SMTP username
    $mail->Password = 'password';           // SMTP password
    $mail->SMTPSecure = 'tls';              // Enable encryption, 'ssl' also accepted

    $mail->From = '[email protected]';
    $mail->FromName = 'name';
    $mail->AddAddress($mailid, $name);       // Name is optional
    $mail->IsHTML(true);                     // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'Here is your message' ;
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
    if (!$mail->Send()) {
       echo 'Message could not be sent.';
       echo 'Mailer Error: ' . $mail->ErrorInfo;
       exit;
    }
    echo 'Message has been sent';
?>
658

Answer

Solution:

If you're stuck with an app hosted on Hostgator, this is what solved my problem. Thanks a lot to the guy who posted the detailed solution. In case the link goes offline one day, there you have the summary:

  • Look for the sendmail path in your server. A simple way to check it, is to temporarily write the following code in a page which only you will access, to read the generated info:<?php phpinfo(); ?>. Open this page, and look forsendmail path. (Then, don't forget to remove this code!)
  • Problem and fix: if your sendmail path is saying only-t -i, then edit your server'sphp.ini and add the following line:sendmail_path = /usr/sbin/sendmail -t -i;

But, after being able to send mail with PHPmail() function, I learned that it sends not authenticated email, what created another issue. The emails were all falling in my Hotmail's junk mail box, and some emails were never delivered, which I guess is related to the fact that they are not authenticated. That's why I decided to switch frommail() toPHPMailer with SMTP, after all.

173

Answer

Solution:

It may be a problem with "From:" $email address in this part of the $headers:

From: \"$name\" <$email>

To try it out, send an email without the headers part, like:

mail('[email protected]', $subject, $message); 

If that is a case, try using an email account that is already created at the system you are trying to send mail from.

784

Answer

Solution:

<?php

$to       = '[email protected]';
$subject  = 'Write your email subject here.';
$message  = '
<html>
<head>
<title>Title here</title>
</head>
<body>
<p>Message here</p>
</body>
</html>
';

// Carriage return type (RFC).
$eol = "\r\n";

$headers  = "Reply-To: Name <[email protected]>".$eol;
$headers .= "Return-Path: Name <[email protected]>".$eol;
$headers .= "From: Name <[email protected]>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/html; charset=iso-8859-1".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;


mail($to, $subject, $message, $headers);

Sending HTML email While sending an email message you can specify a Mime version, content type and character set to send an HTML email.

Example The above example will send an HTML email message to [email protected] You can code this program in such a way that it should receive all content from the user and then it should send an email.

799

Answer

Solution:

What solved this issue for me was that some providers don't allow external recipients when using php mail:

Change the recipient ($recipient) in the code to a local recipient. This means use an email address from the server's domain, for example if your server domain is www.yourdomain.com then the recipient's email should be [email protected] Upload the modified php file and retry. If it's still not working: change the sender ($sender) to a local email (use the same email as used for recipient). Upload the modified php file and retry.

Hope this helps some! https://www.arclab.com/en/kb/php/how-to-test-and-fix-php-mail-function.html

624

Answer

Solution:

I had this problem and found that stripping back the headers helped me to get mail out. So this:

$headers  = "MIME-Version: 1.0;\r\n";
$headers .= "Content-type: text/plain; charset=utf-8;\r\n";
$headers .= "To: ".$recipient."\r\n";
$headers .= "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

became this:

$headers = "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

No need for the To: header.

Mail clients are pretty good at sniffing out URLs and rewriting them as a hyperlink. So I didn't bother writing HTML and specifying text/html in the content-type header. I just threw new lines with \r\n in the message body. I appreciate this isn't the coding purist's approach but it works for what I need it for.

330

Answer

Solution:

There are several possibilities:

  1. You're facing a server problem. The server does not have any mail server. So your mail is not working, because your code is fine and mail is working with type.

  2. You are not getting the posted value. Try your code with a static value.

  3. Use SMTP mails to send mail...

260

Answer

Solution:

Although there are portions of this answer that apply to only to the usage of themail() function itself, many of these troubleshooting steps can be applied to any PHP mailing system.

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.

error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");

See How can I get useful error messages in PHP?this answer for more details on this.

Make sure themail() function is called

It may seem silly but a common error is to forget to actually place themail() function in your code. Make sure it is there and not commented out.

Make sure themail() function is called correctly

bool mail ( string $to, string $subject, string $message [, string $additional_headers [, string $additional_parameters ]] )

The mail function takes three required parameters and optionally a fourth and fifth one. If your call tomail() does not have at least three parameters it will fail.

If your call tomail() does not have the correct parameters in the correct order it will also fail.

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 underlogs. Inside will be error messages the server reported, if any, related to your attempts to send emails.

Check for Port connection failure

Port block is a very common problem which most developers face while integrating their code to deliver emails using SMTP. And, this can be easily traced at the server maillogs (the location of server of mail log can vary from server to server, as explained above). In case you are on a shared hosting server, the ports 25 and 587 remain blocked by default. This block is been purposely done by your hosting provider. This is true even for some of the dedicated servers. When these ports are blocked, try to connect using port 2525. If you find that port is also blocked, then the only solution is to contact your hosting provider to unblock these ports.

Most of the hosting providers block these email ports to protect their network from sending any spam emails.

Use ports 25 or 587 for plain/TLS connections and port 465 for SSL connections. For most users, it is suggested to use port 587 to avoid rate limits set by some hosting providers.

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 right afterwards for concrete failures.

Check themail() return value

The function:

ReturnsTRUE 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 aFALSE 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 you receive aTRUE 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.

SoFALSE will help point you in the right direction whereasTRUE does not necessarily mean your email was sent successfully. This is important to note!

Make sure your hosting provider allows you to send emails and does not limit mail sending

Many shared webhosts, especially free webhosting providers, either do not allow emails to be sent from their servers or limit the amount that can be sent during any given time period. This is due to their efforts to limit spammers from taking advantage of their cheaper services.

If you think your host has emailing limits or blocks the sending of emails, check their FAQs to see if they list any such limitations. Otherwise, you may need to reach out to their support to verify if there are any restrictions in place around the sending of emails.

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" <[email protected]> ).
  • Monitor your abuse accounts, such as[email protected] and[email protected]. 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: [email protected]",
    "Reply-To: [email protected]",
    "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 [email protected]", // missing colon
    "Reply To: [email protected]",      // missing hyphen
    "X-Mailer: "PHP"/" . PHP_VERSION      // bad quotes
);

Don't use a fauxFrom: sender

While the mail must have a From: sender, you may not just use any value. In particular user-supplied sender addresses are a surefire way to get mails blocked:

$headers = array("From: $_POST[contactform_sender_email]"); // No!

Reason: your web or sending mail server is not SPF/DKIM-whitelisted to pretend being responsible for @hotmail or @gmail addresses. It may even silently drop mails withFrom: sender domains it's not configured for.

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 = '[email protected]';
// other variables ....
mail($recipient, $subject, $message, $headers); // $recipient should be $to

Another way to test this is to hard code the recipient value into themail() function call:

mail('[email protected]', $subject, $message, $headers);

This can apply to all of themail() 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 toPOST, make sure you are using$_POST to look for your form values. If you have set it toGET or didn't set it at all, make sure you use$_GET to look for your form values.

Make sure your formaction value points to the correct location

Make sure your formaction attribute contains a value that points to your PHP mailing code.

<form action="send_email.php" method="POST">

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 thelocalhost 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 custommail.log

In addition to your MTA's and PHP's log file, you can enable logging for the 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 http://php.net/manual/en/mail.configuration.php for details. (It's best to enable these options in thephp.ini or.user.ini or.htaccess perhaps.)

Check with a mail testing service

There are various delivery and spamminess checking services you can utilize to test your MTA/webserver setup. Typically you send a mail probe To: their address, then get a delivery report and more concrete failures or analyzations later:

Use a different mailer

PHP's built-inmail() 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:

All of which can be combined with a professional SMTP server/service provider. (Because typical 08/15 shared webhosting plans are hit or miss when it comes to email setup/configurability.)

926

Answer

Solution:

Add a mail header in the mail function:

$header = "From: [email protected]\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);

if($status)
{
    echo '<p>Your mail has been sent!</p>';
} else {
    echo '<p>Something went wrong. Please try again!</p>';
}
271

Answer

Solution:

  1. Always try sending headers in the mail function.
  2. If you are sending mail through localhost then do the SMTP settings for sending mail.
  3. If you are sending mail through a server then check the email sending feature is enabled on your server.
293

Answer

Solution:

If you are using an SMTP configuration for sending your email, try using PHPMailer instead. You can download the library from https://github.com/PHPMailer/PHPMailer.

I created my email sending this way:

function send_mail($email, $recipient_name, $message='')
{
    require("phpmailer/class.phpmailer.php");

    $mail = new PHPMailer();

    $mail->CharSet = "utf-8";
    $mail->IsSMTP();                                      // Set mailer to use SMTP
    $mail->Host = "mail.example.com";  // Specify main and backup server
    $mail->SMTPAuth = true;     // Turn on SMTP authentication
    $mail->Username = "myusername";  // SMTP username
    $mail->Password = "[email protected]"; // SMTP password

    $mail->From = "[email protected]";
    $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');
    $mail->addAttachment('files/file.xlsx');

    if(!$mail->Send())
    {
       echo "Message could not be sent. <p>";
       echo "Mailer Error: " . $mail->ErrorInfo;
       exit;
    }

    echo "Message has been sent";
}
202

Answer

Solution:

Just add some headers before sending mail:

<?php 
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com'; 
$to = '[email protected]'; 
$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: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

And one more thing. Themail() function is not working in localhost. Upload your code to a server and try.

108

Answer

Solution:

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('[email protected]', $subject, $message, $headers)

Use'' and not"".

This code works, but the email was received with half an hour lag.

253

Answer

Solution:

Mostly themail() function is disabled in shared hosting. A better option is to use SMTP. The best option would be Gmail or SendGrid.


SMTPconfig.php

<?php 
    $SmtpServer="smtp.*.*";
    $SmtpPort="2525"; //default
    $SmtpUser="***";
    $SmtpPass="***";
?>

SMTPmail.php

<?php
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;
        }
        else
        {
            $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");
            $talk["res"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpUser."\r\n");
            $talk["user"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpPass."\r\n");
            $talk["pass"]=fgets($SMTPIN,256);
            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");
            $talk["send"]=fgets($SMTPIN,256);
            //CLOSE CONNECTION AND EXIT ... 
            fputs ($SMTPIN, "QUIT\r\n"); 
            fclose($SMTPIN); 
            // 
        } 
        return $talk;
    } 
}
?>

contact_email.php

<?php 
include('SMTPconfig.php');
include('SMTPmail.php');
if($_SERVER["REQUEST_METHOD"] == "POST")
{
    $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();
}
?>
23

Answer

Solution:

If you only use themail()function, you need to complete the configuration file.

You need to open the mail expansion, and set theSMTP smtp_port and so on, and most important, your username and your password. Without that, mail cannot be sent. Also, you can use thePHPMail class to send.

36

Answer

Solution:

Try these two things separately and together:

  1. remove theif($_POST['submit']){}
  2. remove$from (just my gut)
332

Answer

Solution:

I think this should do the trick. I just added anif(isset and added concatenation to the variables in the body to separate PHP from HTML.

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: yoursite.com'; 
    $to = '[email protected]'; 
    $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>';
    } 
    else 
    { 
        echo '<p>Something went wrong, go back and try again!</p>'; 
    }
}

?>
898

Answer

Solution:

For anyone who finds this going forward, I would not recommend usingmail. There's some answers that touch on this, but not the why of it.

PHP'smail 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 frommail. 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 usemail to ultimately send the mail, but I would strongly recommend you not do that).

This means 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 callingisSMTP()), you can get a detailed transcript of the SMTP conversation using theSMTPDebug 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. Withmail 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).

860

Answer

Solution:

$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 class="page_speed_1833695416">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>";
}
853

Answer

Solution:

You can use config email by CodeIgniter. For example, using SMTP (simple way):

$config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'mail.domain.com', // Your SMTP host
        'smtp_port' => 26, // Default port for SMTP
        'smtp_user' => '[email protected]',
        'smtp_pass' => 'password',
        'mailtype' => 'html',
        'charset' => 'iso-8859-1',
        'wordwrap' => TRUE
);
$message = 'Your msg';
$this->load->library('email', $config);
$this->email->from('[email protected]', 'Title');
$this->email->to('[email protected]');
$this->email->subject('Header');
$this->email->message($message);

if($this->email->send()) 
{
   // Conditional true
}

It works for me!

656

Answer

Solution:

Try this

if ($_POST['submit']) {
    $success= mail($to, $subject, $body, $from);
    if($success)
    { 
        echo '
        <p>Your message has been sent!</p>
        ';
    } else { 
        echo '
        <p>Something went wrong, go back and try again!</p>
        '; 
    }
}
424

Answer

Solution:

Maybe the problem is the configuration of the mail server. To avoid this type of problems or you do not have to worry about the mail server problem, I recommend you use PHPMailer.

It is a plugin that has everything necessary to send mail, and the only thing you have to take into account is to have the SMTP port (Port: 25 and 465), enabled.

require_once 'PHPMailer/PHPMailer.php';
require_once '/servicios/PHPMailer/SMTP.php';
require_once '/servicios/PHPMailer/Exception.php';

$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
    //Server settings
    $mail->SMTPDebug = 0;
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = '[email protected]';
    $mail->Password = 'contrasenia';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;

    // Recipients
    $mail->setFrom('[email protected]', 'my name');
    $mail->addAddress('[email protected]');

    // Attachments
    $mail->addAttachment('optional file');         // Add files, is optional

    // Content
    $mail->isHTML(true);// Set email format to HTML
    $mail->Subject = utf8_decode("subject");
    $mail->Body    = utf8_decode("mail content");
    $mail->AltBody = '';
    $mail->send();
}
catch (Exception $e) {
    $error = $mail->ErrorInfo;
}
932

Answer

Solution:

First of all, you might have too many parameters for the mail() function... You are able to have of maximum of five,mail(to, subject, message, headers, parameters);

As far as the$from variable goes, that should automatically come from your webhost if your using the Linux cPanel. It automatically comes from your cPanel username and IP address.

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com';
$to = '[email protected]';
$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.

Themail($to, $subject, $message, etc.) in that order, or else there is a chance of it not working.

7

Answer

Solution:

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 www.AceITLab.com, 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.

343

Answer

Solution:

Make sure you have Sendmail installed in your server.

If you have checked your code and verified that there is nothing wrong there, go to /var/mail and check whether that folder is empty.

If it is empty, you will need to do a:

sudo apt-get install sendmail

if you are on an Ubuntu server.

446

Answer

Solution:

For those who do not want to use external mailers and want to mail() on a dedicated Linux server.

The way, how PHP mails, is described inphp.ini in section[mail function].

Parametersendmail-path describes how sendmail is called. The default value issendmail -t -i, so if you get a workingsendmail -t -i < message.txt in the Linux console - you will be done. You could also addmail.log to debug and be sure mail() is really called.

Different MTAs can implementsendmail. They just make a symbolic link to their binaries on that name. For example, in Debian the default is Postfix. Configure your MTA to send mail and test it from the console withsendmail -v -t -i < message.txt. Filemessage.txt should contain all headers of a message and a body, destination address for the envelope will be taken from theTo: header. Example:

From: [email protected]
To: [email protected]
Subject: Test mail via sendmail.

Text body.

I prefer to use ssmtp as MTA because it is simple and does not require running a daemon with opened ports. ssmtp fits only for sending mail from localhost. It also can send authenticated email via your account on a public mail service. Install ssmtp and edit configuration file/etc/ssmtp/ssmtp.conf. To be able also to receive local system mail to Unix accounts (alerts to root from cron jobs, for example) configure/etc/ssmtp/revaliases file.

Here is my configuration for my account on Yandex mail:

[email protected]
mailhub=smtp.yandex.ru:465
FromLineOverride=YES
UseTLS=YES
[email protected]
AuthPass=password
213

Answer

Solution:

Sendmail installation for Debian 10.0.0 ('Buster') was in fact trivial!

php.ini

[mail function]
sendmail_path=/usr/sbin/sendmail -t -i
; (Other directives are mostly windows)

Standard sendmail package install (allowing 'send'):

su -                                        # Install as user 'root'
dpkg --list                                 # Is install necessary?
apt-get install sendmail sendmail-cf m4     # Note multiple package selection
sendmailconfig                              # Respond all 'Y' for new install

Miscellaneous useful commands:

which sendmail                              # /usr/sbin/sendmail
which sendmailconfig                        # /usr/sbin/sendmailconfig
man sendmail                                # Documentation
systemctl restart sendmail                  # As and when required

Verification (of ability to send)

echo "Subject: sendmail test" | sendmail -v <yourEmail>@gmail.com

The above took about 5 minutes. Then I wasted 5 hours... Don't forget to check your spam folder!

303

Answer

Solution:

If you are running this code on a local server (i.e your computer for development purposes) it won't send the email to the recipient. It will create a.txt file in a folder namedmailoutput.

In the case if you are using a free hosing service, like000webhost orhostinger, those service providers disable themail() 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):

<?php
    $to      = '[email protected]';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: [email protected]' . "\r\n" .
        'Reply-To: [email protected]' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
?>
114

Answer

Solution:

You can use thePHPMailer and it works perfectly,here's a code example:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/phpmailer/phpmailer/src/Exception.php';
require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/phpmailer/src/SMTP.php';
$editor = $_POST["editor"];
$subject = $_POST["subject"];
$to = $_POST["to"];

try {

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->Mailer = "smtp";
        $mail->SMTPDebug  = 1;
        $mail->SMTPAuth   = TRUE;
        $mail->SMTPSecure = "tls";
        $mail->Port       = 587;
        $mail->Host       = "smtp.gmail.com";//using smtp server
        $mail->Username   = "[email protected]";//the email which will send the email 
        $mail->Password   = "XXXXXXXXXX";//the password

        $mail->IsHTML(true);
        $mail->AddAddress($to, "recipient-name");
        $mail->SetFrom("[email protected]", "from-name");
        $mail->AddReplyTo("[email protected]", "reply-to-name");
        $mail->Subject = $subject;
        $mail->MsgHTML($editor);




        if (!$mail->Send()) {
            echo "Error while sending Email.";
            var_dump($mail);
        } else {
            echo "Email sent successfully";
        }
    }
} catch (Exception $e) {
    echo $e->getMessage();
}
656

Answer

Solution:

You can see your errors by:

error_reporting(E_ALL);

And my sample code is:

<?php
    use PHPMailer\PHPMailer\PHPMailer;
    require 'PHPMailer.php';
    require 'SMTP.php';
    require 'Exception.php';

    $name = $_POST['name'];
    $mailid = $_POST['mail'];
    $mail = new PHPMailer;
    $mail->IsSMTP();
    $mail->SMTPDebug = 0;                   // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';         // Specify main and backup server
    $mail->Port = 587;                      // Set the SMTP port
    $mail->SMTPAuth = true;                 // Enable SMTP authentication
    $mail->Username = '[email protected]';  // SMTP username
    $mail->Password = 'password';           // SMTP password
    $mail->SMTPSecure = 'tls';              // Enable encryption, 'ssl' also accepted

    $mail->From = '[email protected]';
    $mail->FromName = 'name';
    $mail->AddAddress($mailid, $name);       // Name is optional
    $mail->IsHTML(true);                     // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'Here is your message' ;
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
    if (!$mail->Send()) {
       echo 'Message could not be sent.';
       echo 'Mailer Error: ' . $mail->ErrorInfo;
       exit;
    }
    echo 'Message has been sent';
?>
520

Answer

Solution:

If you're stuck with an app hosted on Hostgator, this is what solved my problem. Thanks a lot to the guy who posted the detailed solution. In case the link goes offline one day, there you have the summary:

  • Look for the sendmail path in your server. A simple way to check it, is to temporarily write the following code in a page which only you will access, to read the generated info:<?php phpinfo(); ?>. Open this page, and look forsendmail path. (Then, don't forget to remove this code!)
  • Problem and fix: if your sendmail path is saying only-t -i, then edit your server'sphp.ini and add the following line:sendmail_path = /usr/sbin/sendmail -t -i;

But, after being able to send mail with PHPmail() function, I learned that it sends not authenticated email, what created another issue. The emails were all falling in my Hotmail's junk mail box, and some emails were never delivered, which I guess is related to the fact that they are not authenticated. That's why I decided to switch frommail() toPHPMailer with SMTP, after all.

855

Answer

Solution:

It may be a problem with "From:" $email address in this part of the $headers:

From: \"$name\" <$email>

To try it out, send an email without the headers part, like:

mail('[email protected]', $subject, $message); 

If that is a case, try using an email account that is already created at the system you are trying to send mail from.

969

Answer

Solution:

<?php

$to       = '[email protected]';
$subject  = 'Write your email subject here.';
$message  = '
<html>
<head>
<title>Title here</title>
</head>
<body>
<p>Message here</p>
</body>
</html>
';

// Carriage return type (RFC).
$eol = "\r\n";

$headers  = "Reply-To: Name <[email protected]>".$eol;
$headers .= "Return-Path: Name <[email protected]>".$eol;
$headers .= "From: Name <[email protected]>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/html; charset=iso-8859-1".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;


mail($to, $subject, $message, $headers);

Sending HTML email While sending an email message you can specify a Mime version, content type and character set to send an HTML email.

Example The above example will send an HTML email message to [email protected] You can code this program in such a way that it should receive all content from the user and then it should send an email.

403

Answer

Solution:

What solved this issue for me was that some providers don't allow external recipients when using php mail:

Change the recipient ($recipient) in the code to a local recipient. This means use an email address from the server's domain, for example if your server domain is www.yourdomain.com then the recipient's email should be [email protected] Upload the modified php file and retry. If it's still not working: change the sender ($sender) to a local email (use the same email as used for recipient). Upload the modified php file and retry.

Hope this helps some! https://www.arclab.com/en/kb/php/how-to-test-and-fix-php-mail-function.html

746

Answer

Solution:

I had this problem and found that stripping back the headers helped me to get mail out. So this:

$headers  = "MIME-Version: 1.0;\r\n";
$headers .= "Content-type: text/plain; charset=utf-8;\r\n";
$headers .= "To: ".$recipient."\r\n";
$headers .= "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

became this:

$headers = "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

No need for the To: header.

Mail clients are pretty good at sniffing out URLs and rewriting them as a hyperlink. So I didn't bother writing HTML and specifying text/html in the content-type header. I just threw new lines with \r\n in the message body. I appreciate this isn't the coding purist's approach but it works for what I need it for.

463

Answer

Solution:

There are several possibilities:

  1. You're facing a server problem. The server does not have any mail server. So your mail is not working, because your code is fine and mail is working with type.

  2. You are not getting the posted value. Try your code with a static value.

  3. Use SMTP mails to send mail...

330

Answer

Solution:

Although there are portions of this answer that apply to only to the usage of themail() function itself, many of these troubleshooting steps can be applied to any PHP mailing system.

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.

error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");

See How can I get useful error messages in PHP?this answer for more details on this.

Make sure themail() function is called

It may seem silly but a common error is to forget to actually place themail() function in your code. Make sure it is there and not commented out.

Make sure themail() function is called correctly

bool mail ( string $to, string $subject, string $message [, string $additional_headers [, string $additional_parameters ]] )

The mail function takes three required parameters and optionally a fourth and fifth one. If your call tomail() does not have at least three parameters it will fail.

If your call tomail() does not have the correct parameters in the correct order it will also fail.

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 underlogs. Inside will be error messages the server reported, if any, related to your attempts to send emails.

Check for Port connection failure

Port block is a very common problem which most developers face while integrating their code to deliver emails using SMTP. And, this can be easily traced at the server maillogs (the location of server of mail log can vary from server to server, as explained above). In case you are on a shared hosting server, the ports 25 and 587 remain blocked by default. This block is been purposely done by your hosting provider. This is true even for some of the dedicated servers. When these ports are blocked, try to connect using port 2525. If you find that port is also blocked, then the only solution is to contact your hosting provider to unblock these ports.

Most of the hosting providers block these email ports to protect their network from sending any spam emails.

Use ports 25 or 587 for plain/TLS connections and port 465 for SSL connections. For most users, it is suggested to use port 587 to avoid rate limits set by some hosting providers.

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 right afterwards for concrete failures.

Check themail() return value

The function:

ReturnsTRUE 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 aFALSE 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 you receive aTRUE 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.

SoFALSE will help point you in the right direction whereasTRUE does not necessarily mean your email was sent successfully. This is important to note!

Make sure your hosting provider allows you to send emails and does not limit mail sending

Many shared webhosts, especially free webhosting providers, either do not allow emails to be sent from their servers or limit the amount that can be sent during any given time period. This is due to their efforts to limit spammers from taking advantage of their cheaper services.

If you think your host has emailing limits or blocks the sending of emails, check their FAQs to see if they list any such limitations. Otherwise, you may need to reach out to their support to verify if there are any restrictions in place around the sending of emails.

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" <[email protected]> ).
  • Monitor your abuse accounts, such as[email protected] and[email protected]. 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: [email protected]",
    "Reply-To: [email protected]",
    "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 [email protected]", // missing colon
    "Reply To: [email protected]",      // missing hyphen
    "X-Mailer: "PHP"/" . PHP_VERSION      // bad quotes
);

Don't use a fauxFrom: sender

While the mail must have a From: sender, you may not just use any value. In particular user-supplied sender addresses are a surefire way to get mails blocked:

$headers = array("From: $_POST[contactform_sender_email]"); // No!

Reason: your web or sending mail server is not SPF/DKIM-whitelisted to pretend being responsible for @hotmail or @gmail addresses. It may even silently drop mails withFrom: sender domains it's not configured for.

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 = '[email protected]';
// other variables ....
mail($recipient, $subject, $message, $headers); // $recipient should be $to

Another way to test this is to hard code the recipient value into themail() function call:

mail('[email protected]', $subject, $message, $headers);

This can apply to all of themail() 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 toPOST, make sure you are using$_POST to look for your form values. If you have set it toGET or didn't set it at all, make sure you use$_GET to look for your form values.

Make sure your formaction value points to the correct location

Make sure your formaction attribute contains a value that points to your PHP mailing code.

<form action="send_email.php" method="POST">

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 thelocalhost 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 custommail.log

In addition to your MTA's and PHP's log file, you can enable logging for the 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 http://php.net/manual/en/mail.configuration.php for details. (It's best to enable these options in thephp.ini or.user.ini or.htaccess perhaps.)

Check with a mail testing service

There are various delivery and spamminess checking services you can utilize to test your MTA/webserver setup. Typically you send a mail probe To: their address, then get a delivery report and more concrete failures or analyzations later:

Use a different mailer

PHP's built-inmail() 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:

All of which can be combined with a professional SMTP server/service provider. (Because typical 08/15 shared webhosting plans are hit or miss when it comes to email setup/configurability.)

40

Answer

Solution:

Add a mail header in the mail function:

$header = "From: [email protected]\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);

if($status)
{
    echo '<p>Your mail has been sent!</p>';
} else {
    echo '<p>Something went wrong. Please try again!</p>';
}
773

Answer

Solution:

  1. Always try sending headers in the mail function.
  2. If you are sending mail through localhost then do the SMTP settings for sending mail.
  3. If you are sending mail through a server then check the email sending feature is enabled on your server.
132

Answer

Solution:

If you are using an SMTP configuration for sending your email, try using PHPMailer instead. You can download the library from https://github.com/PHPMailer/PHPMailer.

I created my email sending this way:

function send_mail($email, $recipient_name, $message='')
{
    require("phpmailer/class.phpmailer.php");

    $mail = new PHPMailer();

    $mail->CharSet = "utf-8";
    $mail->IsSMTP();                                      // Set mailer to use SMTP
    $mail->Host = "mail.example.com";  // Specify main and backup server
    $mail->SMTPAuth = true;     // Turn on SMTP authentication
    $mail->Username = "myusername";  // SMTP username
    $mail->Password = "[email protected]"; // SMTP password

    $mail->From = "[email protected]";
    $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');
    $mail->addAttachment('files/file.xlsx');

    if(!$mail->Send())
    {
       echo "Message could not be sent. <p>";
       echo "Mailer Error: " . $mail->ErrorInfo;
       exit;
    }

    echo "Message has been sent";
}
654

Answer

Solution:

Just add some headers before sending mail:

<?php 
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com'; 
$to = '[email protected]'; 
$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: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

And one more thing. Themail() function is not working in localhost. Upload your code to a server and try.

618

Answer

Solution:

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('[email protected]', $subject, $message, $headers)

Use'' and not"".

This code works, but the email was received with half an hour lag.

292

Answer

Solution:

Mostly themail() function is disabled in shared hosting. A better option is to use SMTP. The best option would be Gmail or SendGrid.


SMTPconfig.php

<?php 
    $SmtpServer="smtp.*.*";
    $SmtpPort="2525"; //default
    $SmtpUser="***";
    $SmtpPass="***";
?>

SMTPmail.php

<?php
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;
        }
        else
        {
            $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");
            $talk["res"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpUser."\r\n");
            $talk["user"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpPass."\r\n");
            $talk["pass"]=fgets($SMTPIN,256);
            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");
            $talk["send"]=fgets($SMTPIN,256);
            //CLOSE CONNECTION AND EXIT ... 
            fputs ($SMTPIN, "QUIT\r\n"); 
            fclose($SMTPIN); 
            // 
        } 
        return $talk;
    } 
}
?>

contact_email.php

<?php 
include('SMTPconfig.php');
include('SMTPmail.php');
if($_SERVER["REQUEST_METHOD"] == "POST")
{
    $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();
}
?>
732

Answer

Solution:

If you only use themail()function, you need to complete the configuration file.

You need to open the mail expansion, and set theSMTP smtp_port and so on, and most important, your username and your password. Without that, mail cannot be sent. Also, you can use thePHPMail class to send.

600

Answer

Solution:

Try these two things separately and together:

  1. remove theif($_POST['submit']){}
  2. remove$from (just my gut)
534

Answer

Solution:

I think this should do the trick. I just added anif(isset and added concatenation to the variables in the body to separate PHP from HTML.

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: yoursite.com'; 
    $to = '[email protected]'; 
    $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>';
    } 
    else 
    { 
        echo '<p>Something went wrong, go back and try again!</p>'; 
    }
}

?>
390

Answer

Solution:

For anyone who finds this going forward, I would not recommend usingmail. There's some answers that touch on this, but not the why of it.

PHP'smail 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 frommail. 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 usemail to ultimately send the mail, but I would strongly recommend you not do that).

This means 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 callingisSMTP()), you can get a detailed transcript of the SMTP conversation using theSMTPDebug 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. Withmail 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).

820

Answer

Solution:

$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 class="page_speed_1833695416">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>";
}
847

Answer

Solution:

You can use config email by CodeIgniter. For example, using SMTP (simple way):

$config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'mail.domain.com', // Your SMTP host
        'smtp_port' => 26, // Default port for SMTP
        'smtp_user' => '[email protected]',
        'smtp_pass' => 'password',
        'mailtype' => 'html',
        'charset' => 'iso-8859-1',
        'wordwrap' => TRUE
);
$message = 'Your msg';
$this->load->library('email', $config);
$this->email->from('[email protected]', 'Title');
$this->email->to('[email protected]');
$this->email->subject('Header');
$this->email->message($message);

if($this->email->send()) 
{
   // Conditional true
}

It works for me!

422

Answer

Solution:

Try this

if ($_POST['submit']) {
    $success= mail($to, $subject, $body, $from);
    if($success)
    { 
        echo '
        <p>Your message has been sent!</p>
        ';
    } else { 
        echo '
        <p>Something went wrong, go back and try again!</p>
        '; 
    }
}
860

Answer

Solution:

Maybe the problem is the configuration of the mail server. To avoid this type of problems or you do not have to worry about the mail server problem, I recommend you use PHPMailer.

It is a plugin that has everything necessary to send mail, and the only thing you have to take into account is to have the SMTP port (Port: 25 and 465), enabled.

require_once 'PHPMailer/PHPMailer.php';
require_once '/servicios/PHPMailer/SMTP.php';
require_once '/servicios/PHPMailer/Exception.php';

$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
    //Server settings
    $mail->SMTPDebug = 0;
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = '[email protected]';
    $mail->Password = 'contrasenia';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;

    // Recipients
    $mail->setFrom('[email protected]', 'my name');
    $mail->addAddress('[email protected]');

    // Attachments
    $mail->addAttachment('optional file');         // Add files, is optional

    // Content
    $mail->isHTML(true);// Set email format to HTML
    $mail->Subject = utf8_decode("subject");
    $mail->Body    = utf8_decode("mail content");
    $mail->AltBody = '';
    $mail->send();
}
catch (Exception $e) {
    $error = $mail->ErrorInfo;
}
655

Answer

Solution:

First of all, you might have too many parameters for the mail() function... You are able to have of maximum of five,mail(to, subject, message, headers, parameters);

As far as the$from variable goes, that should automatically come from your webhost if your using the Linux cPanel. It automatically comes from your cPanel username and IP address.

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com';
$to = '[email protected]';
$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.

Themail($to, $subject, $message, etc.) in that order, or else there is a chance of it not working.

384

Answer

Solution:

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 www.AceITLab.com, 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.

555

Answer

Solution:

Make sure you have Sendmail installed in your server.

If you have checked your code and verified that there is nothing wrong there, go to /var/mail and check whether that folder is empty.

If it is empty, you will need to do a:

sudo apt-get install sendmail

if you are on an Ubuntu server.

725

Answer

Solution:

For those who do not want to use external mailers and want to mail() on a dedicated Linux server.

The way, how PHP mails, is described inphp.ini in section[mail function].

Parametersendmail-path describes how sendmail is called. The default value issendmail -t -i, so if you get a workingsendmail -t -i < message.txt in the Linux console - you will be done. You could also addmail.log to debug and be sure mail() is really called.

Different MTAs can implementsendmail. They just make a symbolic link to their binaries on that name. For example, in Debian the default is Postfix. Configure your MTA to send mail and test it from the console withsendmail -v -t -i < message.txt. Filemessage.txt should contain all headers of a message and a body, destination address for the envelope will be taken from theTo: header. Example:

From: [email protected]
To: [email protected]
Subject: Test mail via sendmail.

Text body.

I prefer to use ssmtp as MTA because it is simple and does not require running a daemon with opened ports. ssmtp fits only for sending mail from localhost. It also can send authenticated email via your account on a public mail service. Install ssmtp and edit configuration file/etc/ssmtp/ssmtp.conf. To be able also to receive local system mail to Unix accounts (alerts to root from cron jobs, for example) configure/etc/ssmtp/revaliases file.

Here is my configuration for my account on Yandex mail:

[email protected]
mailhub=smtp.yandex.ru:465
FromLineOverride=YES
UseTLS=YES
[email protected]
AuthPass=password
542

Answer

Solution:

Sendmail installation for Debian 10.0.0 ('Buster') was in fact trivial!

php.ini

[mail function]
sendmail_path=/usr/sbin/sendmail -t -i
; (Other directives are mostly windows)

Standard sendmail package install (allowing 'send'):

su -                                        # Install as user 'root'
dpkg --list                                 # Is install necessary?
apt-get install sendmail sendmail-cf m4     # Note multiple package selection
sendmailconfig                              # Respond all 'Y' for new install

Miscellaneous useful commands:

which sendmail                              # /usr/sbin/sendmail
which sendmailconfig                        # /usr/sbin/sendmailconfig
man sendmail                                # Documentation
systemctl restart sendmail                  # As and when required

Verification (of ability to send)

echo "Subject: sendmail test" | sendmail -v <yourEmail>@gmail.com

The above took about 5 minutes. Then I wasted 5 hours... Don't forget to check your spam folder!

576

Answer

Solution:

If you are running this code on a local server (i.e your computer for development purposes) it won't send the email to the recipient. It will create a.txt file in a folder namedmailoutput.

In the case if you are using a free hosing service, like000webhost orhostinger, those service providers disable themail() 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):

<?php
    $to      = '[email protected]';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: [email protected]' . "\r\n" .
        'Reply-To: [email protected]' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
?>
388

Answer

Solution:

You can use thePHPMailer and it works perfectly,here's a code example:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/phpmailer/phpmailer/src/Exception.php';
require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/phpmailer/src/SMTP.php';
$editor = $_POST["editor"];
$subject = $_POST["subject"];
$to = $_POST["to"];

try {

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->Mailer = "smtp";
        $mail->SMTPDebug  = 1;
        $mail->SMTPAuth   = TRUE;
        $mail->SMTPSecure = "tls";
        $mail->Port       = 587;
        $mail->Host       = "smtp.gmail.com";//using smtp server
        $mail->Username   = "[email protected]";//the email which will send the email 
        $mail->Password   = "XXXXXXXXXX";//the password

        $mail->IsHTML(true);
        $mail->AddAddress($to, "recipient-name");
        $mail->SetFrom("[email protected]", "from-name");
        $mail->AddReplyTo("XXXXX[email protected]", "reply-to-name");
        $mail->Subject = $subject;
        $mail->MsgHTML($editor);




        if (!$mail->Send()) {
            echo "Error while sending Email.";
            var_dump($mail);
        } else {
            echo "Email sent successfully";
        }
    }
} catch (Exception $e) {
    echo $e->getMessage();
}
533

Answer

Solution:

You can see your errors by:

error_reporting(E_ALL);

And my sample code is:

<?php
    use PHPMailer\PHPMailer\PHPMailer;
    require 'PHPMailer.php';
    require 'SMTP.php';
    require 'Exception.php';

    $name = $_POST['name'];
    $mailid = $_POST['mail'];
    $mail = new PHPMailer;
    $mail->IsSMTP();
    $mail->SMTPDebug = 0;                   // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';         // Specify main and backup server
    $mail->Port = 587;                      // Set the SMTP port
    $mail->SMTPAuth = true;                 // Enable SMTP authentication
    $mail->Username = '[email protected]';  // SMTP username
    $mail->Password = 'password';           // SMTP password
    $mail->SMTPSecure = 'tls';              // Enable encryption, 'ssl' also accepted

    $mail->From = '[email protected]';
    $mail->FromName = 'name';
    $mail->AddAddress($mailid, $name);       // Name is optional
    $mail->IsHTML(true);                     // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'Here is your message' ;
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
    if (!$mail->Send()) {
       echo 'Message could not be sent.';
       echo 'Mailer Error: ' . $mail->ErrorInfo;
       exit;
    }
    echo 'Message has been sent';
?>
369

Answer

Solution:

If you're stuck with an app hosted on Hostgator, this is what solved my problem. Thanks a lot to the guy who posted the detailed solution. In case the link goes offline one day, there you have the summary:

  • Look for the sendmail path in your server. A simple way to check it, is to temporarily write the following code in a page which only you will access, to read the generated info:<?php phpinfo(); ?>. Open this page, and look forsendmail path. (Then, don't forget to remove this code!)
  • Problem and fix: if your sendmail path is saying only-t -i, then edit your server'sphp.ini and add the following line:sendmail_path = /usr/sbin/sendmail -t -i;

But, after being able to send mail with PHPmail() function, I learned that it sends not authenticated email, what created another issue. The emails were all falling in my Hotmail's junk mail box, and some emails were never delivered, which I guess is related to the fact that they are not authenticated. That's why I decided to switch frommail() toPHPMailer with SMTP, after all.

306

Answer

Solution:

It may be a problem with "From:" $email address in this part of the $headers:

From: \"$name\" <$email>

To try it out, send an email without the headers part, like:

mail('[email protected]', $subject, $message); 

If that is a case, try using an email account that is already created at the system you are trying to send mail from.

677

Answer

Solution:

<?php

$to       = '[email protected]';
$subject  = 'Write your email subject here.';
$message  = '
<html>
<head>
<title>Title here</title>
</head>
<body>
<p>Message here</p>
</body>
</html>
';

// Carriage return type (RFC).
$eol = "\r\n";

$headers  = "Reply-To: Name <[email protected]>".$eol;
$headers .= "Return-Path: Name <[email protected]ample.com>".$eol;
$headers .= "From: Name <[email protected]>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/html; charset=iso-8859-1".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;


mail($to, $subject, $message, $headers);

Sending HTML email While sending an email message you can specify a Mime version, content type and character set to send an HTML email.

Example The above example will send an HTML email message to [email protected] You can code this program in such a way that it should receive all content from the user and then it should send an email.

925

Answer

Solution:

What solved this issue for me was that some providers don't allow external recipients when using php mail:

Change the recipient ($recipient) in the code to a local recipient. This means use an email address from the server's domain, for example if your server domain is www.yourdomain.com then the recipient's email should be [email protected] Upload the modified php file and retry. If it's still not working: change the sender ($sender) to a local email (use the same email as used for recipient). Upload the modified php file and retry.

Hope this helps some! https://www.arclab.com/en/kb/php/how-to-test-and-fix-php-mail-function.html

682

Answer

Solution:

I had this problem and found that stripping back the headers helped me to get mail out. So this:

$headers  = "MIME-Version: 1.0;\r\n";
$headers .= "Content-type: text/plain; charset=utf-8;\r\n";
$headers .= "To: ".$recipient."\r\n";
$headers .= "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

became this:

$headers = "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

No need for the To: header.

Mail clients are pretty good at sniffing out URLs and rewriting them as a hyperlink. So I didn't bother writing HTML and specifying text/html in the content-type header. I just threw new lines with \r\n in the message body. I appreciate this isn't the coding purist's approach but it works for what I need it for.

253

Answer

Solution:

There are several possibilities:

  1. You're facing a server problem. The server does not have any mail server. So your mail is not working, because your code is fine and mail is working with type.

  2. You are not getting the posted value. Try your code with a static value.

  3. Use SMTP mails to send mail...

799

Answer

Solution:

Although there are portions of this answer that apply to only to the usage of themail() function itself, many of these troubleshooting steps can be applied to any PHP mailing system.

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.

error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");

See How can I get useful error messages in PHP?this answer for more details on this.

Make sure themail() function is called

It may seem silly but a common error is to forget to actually place themail() function in your code. Make sure it is there and not commented out.

Make sure themail() function is called correctly

bool mail ( string $to, string $subject, string $message [, string $additional_headers [, string $additional_parameters ]] )

The mail function takes three required parameters and optionally a fourth and fifth one. If your call tomail() does not have at least three parameters it will fail.

If your call tomail() does not have the correct parameters in the correct order it will also fail.

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 underlogs. Inside will be error messages the server reported, if any, related to your attempts to send emails.

Check for Port connection failure

Port block is a very common problem which most developers face while integrating their code to deliver emails using SMTP. And, this can be easily traced at the server maillogs (the location of server of mail log can vary from server to server, as explained above). In case you are on a shared hosting server, the ports 25 and 587 remain blocked by default. This block is been purposely done by your hosting provider. This is true even for some of the dedicated servers. When these ports are blocked, try to connect using port 2525. If you find that port is also blocked, then the only solution is to contact your hosting provider to unblock these ports.

Most of the hosting providers block these email ports to protect their network from sending any spam emails.

Use ports 25 or 587 for plain/TLS connections and port 465 for SSL connections. For most users, it is suggested to use port 587 to avoid rate limits set by some hosting providers.

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 right afterwards for concrete failures.

Check themail() return value

The function:

ReturnsTRUE 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 aFALSE 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 you receive aTRUE 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.

SoFALSE will help point you in the right direction whereasTRUE does not necessarily mean your email was sent successfully. This is important to note!

Make sure your hosting provider allows you to send emails and does not limit mail sending

Many shared webhosts, especially free webhosting providers, either do not allow emails to be sent from their servers or limit the amount that can be sent during any given time period. This is due to their efforts to limit spammers from taking advantage of their cheaper services.

If you think your host has emailing limits or blocks the sending of emails, check their FAQs to see if they list any such limitations. Otherwise, you may need to reach out to their support to verify if there are any restrictions in place around the sending of emails.

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" <[email protected]> ).
  • Monitor your abuse accounts, such as[email protected] and[email protected]. 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: [email protected]",
    "Reply-To: [email protected]",
    "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 [email protected]", // missing colon
    "Reply To: [email protected]",      // missing hyphen
    "X-Mailer: "PHP"/" . PHP_VERSION      // bad quotes
);

Don't use a fauxFrom: sender

While the mail must have a From: sender, you may not just use any value. In particular user-supplied sender addresses are a surefire way to get mails blocked:

$headers = array("From: $_POST[contactform_sender_email]"); // No!

Reason: your web or sending mail server is not SPF/DKIM-whitelisted to pretend being responsible for @hotmail or @gmail addresses. It may even silently drop mails withFrom: sender domains it's not configured for.

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 = '[email protected]';
// other variables ....
mail($recipient, $subject, $message, $headers); // $recipient should be $to

Another way to test this is to hard code the recipient value into themail() function call:

mail('[email protected]', $subject, $message, $headers);

This can apply to all of themail() 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 toPOST, make sure you are using$_POST to look for your form values. If you have set it toGET or didn't set it at all, make sure you use$_GET to look for your form values.

Make sure your formaction value points to the correct location

Make sure your formaction attribute contains a value that points to your PHP mailing code.

<form action="send_email.php" method="POST">

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 thelocalhost 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 custommail.log

In addition to your MTA's and PHP's log file, you can enable logging for the 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 http://php.net/manual/en/mail.configuration.php for details. (It's best to enable these options in thephp.ini or.user.ini or.htaccess perhaps.)

Check with a mail testing service

There are various delivery and spamminess checking services you can utilize to test your MTA/webserver setup. Typically you send a mail probe To: their address, then get a delivery report and more concrete failures or analyzations later:

Use a different mailer

PHP's built-inmail() 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:

All of which can be combined with a professional SMTP server/service provider. (Because typical 08/15 shared webhosting plans are hit or miss when it comes to email setup/configurability.)

884

Answer

Solution:

Add a mail header in the mail function:

$header = "From: [email protected]\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);

if($status)
{
    echo '<p>Your mail has been sent!</p>';
} else {
    echo '<p>Something went wrong. Please try again!</p>';
}
41

Answer

Solution:

  1. Always try sending headers in the mail function.
  2. If you are sending mail through localhost then do the SMTP settings for sending mail.
  3. If you are sending mail through a server then check the email sending feature is enabled on your server.
135

Answer

Solution:

If you are using an SMTP configuration for sending your email, try using PHPMailer instead. You can download the library from https://github.com/PHPMailer/PHPMailer.

I created my email sending this way:

function send_mail($email, $recipient_name, $message='')
{
    require("phpmailer/class.phpmailer.php");

    $mail = new PHPMailer();

    $mail->CharSet = "utf-8";
    $mail->IsSMTP();                                      // Set mailer to use SMTP
    $mail->Host = "mail.example.com";  // Specify main and backup server
    $mail->SMTPAuth = true;     // Turn on SMTP authentication
    $mail->Username = "myusername";  // SMTP username
    $mail->Password = "[email protected]"; // SMTP password

    $mail->From = "[email protected]";
    $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');
    $mail->addAttachment('files/file.xlsx');

    if(!$mail->Send())
    {
       echo "Message could not be sent. <p>";
       echo "Mailer Error: " . $mail->ErrorInfo;
       exit;
    }

    echo "Message has been sent";
}
523

Answer

Solution:

Just add some headers before sending mail:

<?php 
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com'; 
$to = '[email protected]'; 
$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: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

And one more thing. Themail() function is not working in localhost. Upload your code to a server and try.

160

Answer

Solution:

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('[email protected]', $subject, $message, $headers)

Use'' and not"".

This code works, but the email was received with half an hour lag.

960

Answer

Solution:

Mostly themail() function is disabled in shared hosting. A better option is to use SMTP. The best option would be Gmail or SendGrid.


SMTPconfig.php

<?php 
    $SmtpServer="smtp.*.*";
    $SmtpPort="2525"; //default
    $SmtpUser="***";
    $SmtpPass="***";
?>

SMTPmail.php

<?php
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;
        }
        else
        {
            $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");
            $talk["res"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpUser."\r\n");
            $talk["user"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpPass."\r\n");
            $talk["pass"]=fgets($SMTPIN,256);
            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");
            $talk["send"]=fgets($SMTPIN,256);
            //CLOSE CONNECTION AND EXIT ... 
            fputs ($SMTPIN, "QUIT\r\n"); 
            fclose($SMTPIN); 
            // 
        } 
        return $talk;
    } 
}
?>

contact_email.php

<?php 
include('SMTPconfig.php');
include('SMTPmail.php');
if($_SERVER["REQUEST_METHOD"] == "POST")
{
    $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();
}
?>
123

Answer

Solution:

If you only use themail()function, you need to complete the configuration file.

You need to open the mail expansion, and set theSMTP smtp_port and so on, and most important, your username and your password. Without that, mail cannot be sent. Also, you can use thePHPMail class to send.

340

Answer

Solution:

Try these two things separately and together:

  1. remove theif($_POST['submit']){}
  2. remove$from (just my gut)
24

Answer

Solution:

I think this should do the trick. I just added anif(isset and added concatenation to the variables in the body to separate PHP from HTML.

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: yoursite.com'; 
    $to = '[email protected]'; 
    $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>';
    } 
    else 
    { 
        echo '<p>Something went wrong, go back and try again!</p>'; 
    }
}

?>
442

Answer

Solution:

For anyone who finds this going forward, I would not recommend usingmail. There's some answers that touch on this, but not the why of it.

PHP'smail 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 frommail. 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 usemail to ultimately send the mail, but I would strongly recommend you not do that).

This means 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 callingisSMTP()), you can get a detailed transcript of the SMTP conversation using theSMTPDebug 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. Withmail 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).

601

Answer

Solution:

$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 class="page_speed_1833695416">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>";
}
244

Answer

Solution:

You can use config email by CodeIgniter. For example, using SMTP (simple way):

$config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'mail.domain.com', // Your SMTP host
        'smtp_port' => 26, // Default port for SMTP
        'smtp_user' => '[email protected]',
        'smtp_pass' => 'password',
        'mailtype' => 'html',
        'charset' => 'iso-8859-1',
        'wordwrap' => TRUE
);
$message = 'Your msg';
$this->load->library('email', $config);
$this->email->from('[email protected]', 'Title');
$this->email->to('[email protected]');
$this->email->subject('Header');
$this->email->message($message);

if($this->email->send()) 
{
   // Conditional true
}

It works for me!

694

Answer

Solution:

Try this

if ($_POST['submit']) {
    $success= mail($to, $subject, $body, $from);
    if($success)
    { 
        echo '
        <p>Your message has been sent!</p>
        ';
    } else { 
        echo '
        <p>Something went wrong, go back and try again!</p>
        '; 
    }
}
58

Answer

Solution:

Maybe the problem is the configuration of the mail server. To avoid this type of problems or you do not have to worry about the mail server problem, I recommend you use PHPMailer.

It is a plugin that has everything necessary to send mail, and the only thing you have to take into account is to have the SMTP port (Port: 25 and 465), enabled.

require_once 'PHPMailer/PHPMailer.php';
require_once '/servicios/PHPMailer/SMTP.php';
require_once '/servicios/PHPMailer/Exception.php';

$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
    //Server settings
    $mail->SMTPDebug = 0;
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = '[email protected]';
    $mail->Password = 'contrasenia';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;

    // Recipients
    $mail->setFrom('[email protected]', 'my name');
    $mail->addAddress('[email protected]');

    // Attachments
    $mail->addAttachment('optional file');         // Add files, is optional

    // Content
    $mail->isHTML(true);// Set email format to HTML
    $mail->Subject = utf8_decode("subject");
    $mail->Body    = utf8_decode("mail content");
    $mail->AltBody = '';
    $mail->send();
}
catch (Exception $e) {
    $error = $mail->ErrorInfo;
}
414

Answer

Solution:

First of all, you might have too many parameters for the mail() function... You are able to have of maximum of five,mail(to, subject, message, headers, parameters);

As far as the$from variable goes, that should automatically come from your webhost if your using the Linux cPanel. It automatically comes from your cPanel username and IP address.

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com';
$to = '[email protected]';
$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.

Themail($to, $subject, $message, etc.) in that order, or else there is a chance of it not working.

260

Answer

Solution:

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 www.AceITLab.com, 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.

756

Answer

Solution:

Make sure you have Sendmail installed in your server.

If you have checked your code and verified that there is nothing wrong there, go to /var/mail and check whether that folder is empty.

If it is empty, you will need to do a:

sudo apt-get install sendmail

if you are on an Ubuntu server.

102

Answer

Solution:

For those who do not want to use external mailers and want to mail() on a dedicated Linux server.

The way, how PHP mails, is described inphp.ini in section[mail function].

Parametersendmail-path describes how sendmail is called. The default value issendmail -t -i, so if you get a workingsendmail -t -i < message.txt in the Linux console - you will be done. You could also addmail.log to debug and be sure mail() is really called.

Different MTAs can implementsendmail. They just make a symbolic link to their binaries on that name. For example, in Debian the default is Postfix. Configure your MTA to send mail and test it from the console withsendmail -v -t -i < message.txt. Filemessage.txt should contain all headers of a message and a body, destination address for the envelope will be taken from theTo: header. Example:

From: [email protected]
To: [email protected]
Subject: Test mail via sendmail.

Text body.

I prefer to use ssmtp as MTA because it is simple and does not require running a daemon with opened ports. ssmtp fits only for sending mail from localhost. It also can send authenticated email via your account on a public mail service. Install ssmtp and edit configuration file/etc/ssmtp/ssmtp.conf. To be able also to receive local system mail to Unix accounts (alerts to root from cron jobs, for example) configure/etc/ssmtp/revaliases file.

Here is my configuration for my account on Yandex mail:

[email protected]
mailhub=smtp.yandex.ru:465
FromLineOverride=YES
UseTLS=YES
[email protected]
AuthPass=password
86

Answer

Solution:

Sendmail installation for Debian 10.0.0 ('Buster') was in fact trivial!

php.ini

[mail function]
sendmail_path=/usr/sbin/sendmail -t -i
; (Other directives are mostly windows)

Standard sendmail package install (allowing 'send'):

su -                                        # Install as user 'root'
dpkg --list                                 # Is install necessary?
apt-get install sendmail sendmail-cf m4     # Note multiple package selection
sendmailconfig                              # Respond all 'Y' for new install

Miscellaneous useful commands:

which sendmail                              # /usr/sbin/sendmail
which sendmailconfig                        # /usr/sbin/sendmailconfig
man sendmail                                # Documentation
systemctl restart sendmail                  # As and when required

Verification (of ability to send)

echo "Subject: sendmail test" | sendmail -v <yourEmail>@gmail.com

The above took about 5 minutes. Then I wasted 5 hours... Don't forget to check your spam folder!

396

Answer

Solution:

If you are running this code on a local server (i.e your computer for development purposes) it won't send the email to the recipient. It will create a.txt file in a folder namedmailoutput.

In the case if you are using a free hosing service, like000webhost orhostinger, those service providers disable themail() 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):

<?php
    $to      = '[email protected]';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: [email protected]' . "\r\n" .
        'Reply-To: [email protected]' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
?>
234

Answer

Solution:

You can use thePHPMailer and it works perfectly,here's a code example:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/phpmailer/phpmailer/src/Exception.php';
require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/phpmailer/src/SMTP.php';
$editor = $_POST["editor"];
$subject = $_POST["subject"];
$to = $_POST["to"];

try {

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->Mailer = "smtp";
        $mail->SMTPDebug  = 1;
        $mail->SMTPAuth   = TRUE;
        $mail->SMTPSecure = "tls";
        $mail->Port       = 587;
        $mail->Host       = "smtp.gmail.com";//using smtp server
        $mail->Username   = "[email protected]";//the email which will send the email 
        $mail->Password   = "XXXXXXXXXX";//the password

        $mail->IsHTML(true);
        $mail->AddAddress($to, "recipient-name");
        $mail->SetFrom("[email protected]", "from-name");
        $mail->AddReplyTo("[email protected]", "reply-to-name");
        $mail->Subject = $subject;
        $mail->MsgHTML($editor);




        if (!$mail->Send()) {
            echo "Error while sending Email.";
            var_dump($mail);
        } else {
            echo "Email sent successfully";
        }
    }
} catch (Exception $e) {
    echo $e->getMessage();
}
880

Answer

Solution:

You can see your errors by:

error_reporting(E_ALL);

And my sample code is:

<?php
    use PHPMailer\PHPMailer\PHPMailer;
    require 'PHPMailer.php';
    require 'SMTP.php';
    require 'Exception.php';

    $name = $_POST['name'];
    $mailid = $_POST['mail'];
    $mail = new PHPMailer;
    $mail->IsSMTP();
    $mail->SMTPDebug = 0;                   // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';         // Specify main and backup server
    $mail->Port = 587;                      // Set the SMTP port
    $mail->SMTPAuth = true;                 // Enable SMTP authentication
    $mail->Username = '[email protected]';  // SMTP username
    $mail->Password = 'password';           // SMTP password
    $mail->SMTPSecure = 'tls';              // Enable encryption, 'ssl' also accepted

    $mail->From = '[email protected]';
    $mail->FromName = 'name';
    $mail->AddAddress($mailid, $name);       // Name is optional
    $mail->IsHTML(true);                     // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'Here is your message' ;
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
    if (!$mail->Send()) {
       echo 'Message could not be sent.';
       echo 'Mailer Error: ' . $mail->ErrorInfo;
       exit;
    }
    echo 'Message has been sent';
?>
570

Answer

Solution:

If you're stuck with an app hosted on Hostgator, this is what solved my problem. Thanks a lot to the guy who posted the detailed solution. In case the link goes offline one day, there you have the summary:

  • Look for the sendmail path in your server. A simple way to check it, is to temporarily write the following code in a page which only you will access, to read the generated info:<?php phpinfo(); ?>. Open this page, and look forsendmail path. (Then, don't forget to remove this code!)
  • Problem and fix: if your sendmail path is saying only-t -i, then edit your server'sphp.ini and add the following line:sendmail_path = /usr/sbin/sendmail -t -i;

But, after being able to send mail with PHPmail() function, I learned that it sends not authenticated email, what created another issue. The emails were all falling in my Hotmail's junk mail box, and some emails were never delivered, which I guess is related to the fact that they are not authenticated. That's why I decided to switch frommail() toPHPMailer with SMTP, after all.

915

Answer

Solution:

It may be a problem with "From:" $email address in this part of the $headers:

From: \"$name\" <$email>

To try it out, send an email without the headers part, like:

mail('[email protected]', $subject, $message); 

If that is a case, try using an email account that is already created at the system you are trying to send mail from.

479

Answer

Solution:

<?php

$to       = '[email protected]';
$subject  = 'Write your email subject here.';
$message  = '
<html>
<head>
<title>Title here</title>
</head>
<body>
<p>Message here</p>
</body>
</html>
';

// Carriage return type (RFC).
$eol = "\r\n";

$headers  = "Reply-To: Name <[email protected]>".$eol;
$headers .= "Return-Path: Name <[email protected]>".$eol;
$headers .= "From: Name <[email protected]>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/html; charset=iso-8859-1".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;


mail($to, $subject, $message, $headers);

Sending HTML email While sending an email message you can specify a Mime version, content type and character set to send an HTML email.

Example The above example will send an HTML email message to [email protected] You can code this program in such a way that it should receive all content from the user and then it should send an email.

93

Answer

Solution:

What solved this issue for me was that some providers don't allow external recipients when using php mail:

Change the recipient ($recipient) in the code to a local recipient. This means use an email address from the server's domain, for example if your server domain is www.yourdomain.com then the recipient's email should be [email protected] Upload the modified php file and retry. If it's still not working: change the sender ($sender) to a local email (use the same email as used for recipient). Upload the modified php file and retry.

Hope this helps some! https://www.arclab.com/en/kb/php/how-to-test-and-fix-php-mail-function.html

639

Answer

Solution:

I had this problem and found that stripping back the headers helped me to get mail out. So this:

$headers  = "MIME-Version: 1.0;\r\n";
$headers .= "Content-type: text/plain; charset=utf-8;\r\n";
$headers .= "To: ".$recipient."\r\n";
$headers .= "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

became this:

$headers = "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

No need for the To: header.

Mail clients are pretty good at sniffing out URLs and rewriting them as a hyperlink. So I didn't bother writing HTML and specifying text/html in the content-type header. I just threw new lines with \r\n in the message body. I appreciate this isn't the coding purist's approach but it works for what I need it for.

649

Answer

Solution:

There are several possibilities:

  1. You're facing a server problem. The server does not have any mail server. So your mail is not working, because your code is fine and mail is working with type.

  2. You are not getting the posted value. Try your code with a static value.

  3. Use SMTP mails to send mail...

189

Answer

Solution:

Although there are portions of this answer that apply to only to the usage of themail() function itself, many of these troubleshooting steps can be applied to any PHP mailing system.

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.

error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");

See How can I get useful error messages in PHP?this answer for more details on this.

Make sure themail() function is called

It may seem silly but a common error is to forget to actually place themail() function in your code. Make sure it is there and not commented out.

Make sure themail() function is called correctly

bool mail ( string $to, string $subject, string $message [, string $additional_headers [, string $additional_parameters ]] )

The mail function takes three required parameters and optionally a fourth and fifth one. If your call tomail() does not have at least three parameters it will fail.

If your call tomail() does not have the correct parameters in the correct order it will also fail.

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 underlogs. Inside will be error messages the server reported, if any, related to your attempts to send emails.

Check for Port connection failure

Port block is a very common problem which most developers face while integrating their code to deliver emails using SMTP. And, this can be easily traced at the server maillogs (the location of server of mail log can vary from server to server, as explained above). In case you are on a shared hosting server, the ports 25 and 587 remain blocked by default. This block is been purposely done by your hosting provider. This is true even for some of the dedicated servers. When these ports are blocked, try to connect using port 2525. If you find that port is also blocked, then the only solution is to contact your hosting provider to unblock these ports.

Most of the hosting providers block these email ports to protect their network from sending any spam emails.

Use ports 25 or 587 for plain/TLS connections and port 465 for SSL connections. For most users, it is suggested to use port 587 to avoid rate limits set by some hosting providers.

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 right afterwards for concrete failures.

Check themail() return value

The function:

ReturnsTRUE 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 aFALSE 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 you receive aTRUE 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.

SoFALSE will help point you in the right direction whereasTRUE does not necessarily mean your email was sent successfully. This is important to note!

Make sure your hosting provider allows you to send emails and does not limit mail sending

Many shared webhosts, especially free webhosting providers, either do not allow emails to be sent from their servers or limit the amount that can be sent during any given time period. This is due to their efforts to limit spammers from taking advantage of their cheaper services.

If you think your host has emailing limits or blocks the sending of emails, check their FAQs to see if they list any such limitations. Otherwise, you may need to reach out to their support to verify if there are any restrictions in place around the sending of emails.

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" <[email protected]> ).
  • Monitor your abuse accounts, such as[email protected] and[email protected]. 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: [email protected]",
    "Reply-To: [email protected]",
    "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 [email protected]", // missing colon
    "Reply To: [email protected]",      // missing hyphen
    "X-Mailer: "PHP"/" . PHP_VERSION      // bad quotes
);

Don't use a fauxFrom: sender

While the mail must have a From: sender, you may not just use any value. In particular user-supplied sender addresses are a surefire way to get mails blocked:

$headers = array("From: $_POST[contactform_sender_email]"); // No!

Reason: your web or sending mail server is not SPF/DKIM-whitelisted to pretend being responsible for @hotmail or @gmail addresses. It may even silently drop mails withFrom: sender domains it's not configured for.

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 = '[email protected]';
// other variables ....
mail($recipient, $subject, $message, $headers); // $recipient should be $to

Another way to test this is to hard code the recipient value into themail() function call:

mail('[email protected]', $subject, $message, $headers);

This can apply to all of themail() 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 toPOST, make sure you are using$_POST to look for your form values. If you have set it toGET or didn't set it at all, make sure you use$_GET to look for your form values.

Make sure your formaction value points to the correct location

Make sure your formaction attribute contains a value that points to your PHP mailing code.

<form action="send_email.php" method="POST">

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 thelocalhost 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 custommail.log

In addition to your MTA's and PHP's log file, you can enable logging for the 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 http://php.net/manual/en/mail.configuration.php for details. (It's best to enable these options in thephp.ini or.user.ini or.htaccess perhaps.)

Check with a mail testing service

There are various delivery and spamminess checking services you can utilize to test your MTA/webserver setup. Typically you send a mail probe To: their address, then get a delivery report and more concrete failures or analyzations later:

Use a different mailer

PHP's built-inmail() 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:

All of which can be combined with a professional SMTP server/service provider. (Because typical 08/15 shared webhosting plans are hit or miss when it comes to email setup/configurability.)

273

Answer

Solution:

Add a mail header in the mail function:

$header = "From: [email protected]\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);

if($status)
{
    echo '<p>Your mail has been sent!</p>';
} else {
    echo '<p>Something went wrong. Please try again!</p>';
}
854

Answer

Solution:

  1. Always try sending headers in the mail function.
  2. If you are sending mail through localhost then do the SMTP settings for sending mail.
  3. If you are sending mail through a server then check the email sending feature is enabled on your server.
203

Answer

Solution:

If you are using an SMTP configuration for sending your email, try using PHPMailer instead. You can download the library from https://github.com/PHPMailer/PHPMailer.

I created my email sending this way:

function send_mail($email, $recipient_name, $message='')
{
    require("phpmailer/class.phpmailer.php");

    $mail = new PHPMailer();

    $mail->CharSet = "utf-8";
    $mail->IsSMTP();                                      // Set mailer to use SMTP
    $mail->Host = "mail.example.com";  // Specify main and backup server
    $mail->SMTPAuth = true;     // Turn on SMTP authentication
    $mail->Username = "myusername";  // SMTP username
    $mail->Password = "[email protected]"; // SMTP password

    $mail->From = "[email protected]";
    $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');
    $mail->addAttachment('files/file.xlsx');

    if(!$mail->Send())
    {
       echo "Message could not be sent. <p>";
       echo "Mailer Error: " . $mail->ErrorInfo;
       exit;
    }

    echo "Message has been sent";
}
826

Answer

Solution:

Just add some headers before sending mail:

<?php 
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com'; 
$to = '[email protected]'; 
$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: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

And one more thing. Themail() function is not working in localhost. Upload your code to a server and try.

823

Answer

Solution:

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('[email protected]', $subject, $message, $headers)

Use'' and not"".

This code works, but the email was received with half an hour lag.

842

Answer

Solution:

Mostly themail() function is disabled in shared hosting. A better option is to use SMTP. The best option would be Gmail or SendGrid.


SMTPconfig.php

<?php 
    $SmtpServer="smtp.*.*";
    $SmtpPort="2525"; //default
    $SmtpUser="***";
    $SmtpPass="***";
?>

SMTPmail.php

<?php
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;
        }
        else
        {
            $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");
            $talk["res"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpUser."\r\n");
            $talk["user"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpPass."\r\n");
            $talk["pass"]=fgets($SMTPIN,256);
            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");
            $talk["send"]=fgets($SMTPIN,256);
            //CLOSE CONNECTION AND EXIT ... 
            fputs ($SMTPIN, "QUIT\r\n"); 
            fclose($SMTPIN); 
            // 
        } 
        return $talk;
    } 
}
?>

contact_email.php

<?php 
include('SMTPconfig.php');
include('SMTPmail.php');
if($_SERVER["REQUEST_METHOD"] == "POST")
{
    $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();
}
?>
945

Answer

Solution:

If you only use themail()function, you need to complete the configuration file.

You need to open the mail expansion, and set theSMTP smtp_port and so on, and most important, your username and your password. Without that, mail cannot be sent. Also, you can use thePHPMail class to send.

718

Answer

Solution:

Try these two things separately and together:

  1. remove theif($_POST['submit']){}
  2. remove$from (just my gut)
440

Answer

Solution:

I think this should do the trick. I just added anif(isset and added concatenation to the variables in the body to separate PHP from HTML.

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: yoursite.com'; 
    $to = '[email protected]'; 
    $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>';
    } 
    else 
    { 
        echo '<p>Something went wrong, go back and try again!</p>'; 
    }
}

?>
848

Answer

Solution:

For anyone who finds this going forward, I would not recommend usingmail. There's some answers that touch on this, but not the why of it.

PHP'smail 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 frommail. 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 usemail to ultimately send the mail, but I would strongly recommend you not do that).

This means 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 callingisSMTP()), you can get a detailed transcript of the SMTP conversation using theSMTPDebug 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. Withmail 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).

742

Answer

Solution:

$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 class="page_speed_1833695416">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>";
}
852

Answer

Solution:

You can use config email by CodeIgniter. For example, using SMTP (simple way):

$config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'mail.domain.com', // Your SMTP host
        'smtp_port' => 26, // Default port for SMTP
        'smtp_user' => '[email protected]',
        'smtp_pass' => 'password',
        'mailtype' => 'html',
        'charset' => 'iso-8859-1',
        'wordwrap' => TRUE
);
$message = 'Your msg';
$this->load->library('email', $config);
$this->email->from('[email protected]', 'Title');
$this->email->to('[email protected]');
$this->email->subject('Header');
$this->email->message($message);

if($this->email->send()) 
{
   // Conditional true
}

It works for me!

443

Answer

Solution:

Try this

if ($_POST['submit']) {
    $success= mail($to, $subject, $body, $from);
    if($success)
    { 
        echo '
        <p>Your message has been sent!</p>
        ';
    } else { 
        echo '
        <p>Something went wrong, go back and try again!</p>
        '; 
    }
}
398

Answer

Solution:

Maybe the problem is the configuration of the mail server. To avoid this type of problems or you do not have to worry about the mail server problem, I recommend you use PHPMailer.

It is a plugin that has everything necessary to send mail, and the only thing you have to take into account is to have the SMTP port (Port: 25 and 465), enabled.

require_once 'PHPMailer/PHPMailer.php';
require_once '/servicios/PHPMailer/SMTP.php';
require_once '/servicios/PHPMailer/Exception.php';

$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
    //Server settings
    $mail->SMTPDebug = 0;
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = '[email protected]';
    $mail->Password = 'contrasenia';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;

    // Recipients
    $mail->setFrom('[email protected]', 'my name');
    $mail->addAddress('[email protected]');

    // Attachments
    $mail->addAttachment('optional file');         // Add files, is optional

    // Content
    $mail->isHTML(true);// Set email format to HTML
    $mail->Subject = utf8_decode("subject");
    $mail->Body    = utf8_decode("mail content");
    $mail->AltBody = '';
    $mail->send();
}
catch (Exception $e) {
    $error = $mail->ErrorInfo;
}
296

Answer

Solution:

First of all, you might have too many parameters for the mail() function... You are able to have of maximum of five,mail(to, subject, message, headers, parameters);

As far as the$from variable goes, that should automatically come from your webhost if your using the Linux cPanel. It automatically comes from your cPanel username and IP address.

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com';
$to = '[email protected]';
$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.

Themail($to, $subject, $message, etc.) in that order, or else there is a chance of it not working.

692

Answer

Solution:

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 www.AceITLab.com, 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.

767

Answer

Solution:

Make sure you have Sendmail installed in your server.

If you have checked your code and verified that there is nothing wrong there, go to /var/mail and check whether that folder is empty.

If it is empty, you will need to do a:

sudo apt-get install sendmail

if you are on an Ubuntu server.

131

Answer

Solution:

For those who do not want to use external mailers and want to mail() on a dedicated Linux server.

The way, how PHP mails, is described inphp.ini in section[mail function].

Parametersendmail-path describes how sendmail is called. The default value issendmail -t -i, so if you get a workingsendmail -t -i < message.txt in the Linux console - you will be done. You could also addmail.log to debug and be sure mail() is really called.

Different MTAs can implementsendmail. They just make a symbolic link to their binaries on that name. For example, in Debian the default is Postfix. Configure your MTA to send mail and test it from the console withsendmail -v -t -i < message.txt. Filemessage.txt should contain all headers of a message and a body, destination address for the envelope will be taken from theTo: header. Example:

From: [email protected]
To: [email protected]
Subject: Test mail via sendmail.

Text body.

I prefer to use ssmtp as MTA because it is simple and does not require running a daemon with opened ports. ssmtp fits only for sending mail from localhost. It also can send authenticated email via your account on a public mail service. Install ssmtp and edit configuration file/etc/ssmtp/ssmtp.conf. To be able also to receive local system mail to Unix accounts (alerts to root from cron jobs, for example) configure/etc/ssmtp/revaliases file.

Here is my configuration for my account on Yandex mail:

[email protected]
mailhub=smtp.yandex.ru:465
FromLineOverride=YES
UseTLS=YES
[email protected]
AuthPass=password
258

Answer

Solution:

Sendmail installation for Debian 10.0.0 ('Buster') was in fact trivial!

php.ini

[mail function]
sendmail_path=/usr/sbin/sendmail -t -i
; (Other directives are mostly windows)

Standard sendmail package install (allowing 'send'):

su -                                        # Install as user 'root'
dpkg --list                                 # Is install necessary?
apt-get install sendmail sendmail-cf m4     # Note multiple package selection
sendmailconfig                              # Respond all 'Y' for new install

Miscellaneous useful commands:

which sendmail                              # /usr/sbin/sendmail
which sendmailconfig                        # /usr/sbin/sendmailconfig
man sendmail                                # Documentation
systemctl restart sendmail                  # As and when required

Verification (of ability to send)

echo "Subject: sendmail test" | sendmail -v <yourEmail>@gmail.com

The above took about 5 minutes. Then I wasted 5 hours... Don't forget to check your spam folder!

81

Answer

Solution:

If you are running this code on a local server (i.e your computer for development purposes) it won't send the email to the recipient. It will create a.txt file in a folder namedmailoutput.

In the case if you are using a free hosing service, like000webhost orhostinger, those service providers disable themail() 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):

<?php
    $to      = '[email protected]';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: [email protected]' . "\r\n" .
        'Reply-To: [email protected]' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
?>
667

Answer

Solution:

You can use thePHPMailer and it works perfectly,here's a code example:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/phpmailer/phpmailer/src/Exception.php';
require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/phpmailer/src/SMTP.php';
$editor = $_POST["editor"];
$subject = $_POST["subject"];
$to = $_POST["to"];

try {

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->Mailer = "smtp";
        $mail->SMTPDebug  = 1;
        $mail->SMTPAuth   = TRUE;
        $mail->SMTPSecure = "tls";
        $mail->Port       = 587;
        $mail->Host       = "smtp.gmail.com";//using smtp server
        $mail->Username   = "[email protected]";//the email which will send the email 
        $mail->Password   = "XXXXXXXXXX";//the password

        $mail->IsHTML(true);
        $mail->AddAddress($to, "recipient-name");
        $mail->SetFrom("[email protected]", "from-name");
        $mail->AddReplyTo("[email protected]", "reply-to-name");
        $mail->Subject = $subject;
        $mail->MsgHTML($editor);




        if (!$mail->Send()) {
            echo "Error while sending Email.";
            var_dump($mail);
        } else {
            echo "Email sent successfully";
        }
    }
} catch (Exception $e) {
    echo $e->getMessage();
}
300

Answer

Solution:

You can see your errors by:

error_reporting(E_ALL);

And my sample code is:

<?php
    use PHPMailer\PHPMailer\PHPMailer;
    require 'PHPMailer.php';
    require 'SMTP.php';
    require 'Exception.php';

    $name = $_POST['name'];
    $mailid = $_POST['mail'];
    $mail = new PHPMailer;
    $mail->IsSMTP();
    $mail->SMTPDebug = 0;                   // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';         // Specify main and backup server
    $mail->Port = 587;                      // Set the SMTP port
    $mail->SMTPAuth = true;                 // Enable SMTP authentication
    $mail->Username = '[email protected]';  // SMTP username
    $mail->Password = 'password';           // SMTP password
    $mail->SMTPSecure = 'tls';              // Enable encryption, 'ssl' also accepted

    $mail->From = '[email protected]';
    $mail->FromName = 'name';
    $mail->AddAddress($mailid, $name);       // Name is optional
    $mail->IsHTML(true);                     // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'Here is your message' ;
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
    if (!$mail->Send()) {
       echo 'Message could not be sent.';
       echo 'Mailer Error: ' . $mail->ErrorInfo;
       exit;
    }
    echo 'Message has been sent';
?>
79

Answer

Solution:

If you're stuck with an app hosted on Hostgator, this is what solved my problem. Thanks a lot to the guy who posted the detailed solution. In case the link goes offline one day, there you have the summary:

  • Look for the sendmail path in your server. A simple way to check it, is to temporarily write the following code in a page which only you will access, to read the generated info:<?php phpinfo(); ?>. Open this page, and look forsendmail path. (Then, don't forget to remove this code!)
  • Problem and fix: if your sendmail path is saying only-t -i, then edit your server'sphp.ini and add the following line:sendmail_path = /usr/sbin/sendmail -t -i;

But, after being able to send mail with PHPmail() function, I learned that it sends not authenticated email, what created another issue. The emails were all falling in my Hotmail's junk mail box, and some emails were never delivered, which I guess is related to the fact that they are not authenticated. That's why I decided to switch frommail() toPHPMailer with SMTP, after all.

62

Answer

Solution:

It may be a problem with "From:" $email address in this part of the $headers:

From: \"$name\" <$email>

To try it out, send an email without the headers part, like:

mail('[email protected]', $subject, $message); 

If that is a case, try using an email account that is already created at the system you are trying to send mail from.

807

Answer

Solution:

<?php

$to       = '[email protected]';
$subject  = 'Write your email subject here.';
$message  = '
<html>
<head>
<title>Title here</title>
</head>
<body>
<p>Message here</p>
</body>
</html>
';

// Carriage return type (RFC).
$eol = "\r\n";

$headers  = "Reply-To: Name <[email protected]>".$eol;
$headers .= "Return-Path: Name <[email protected]>".$eol;
$headers .= "From: Name <[email protected]>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/html; charset=iso-8859-1".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;


mail($to, $subject, $message, $headers);

Sending HTML email While sending an email message you can specify a Mime version, content type and character set to send an HTML email.

Example The above example will send an HTML email message to [email protected] You can code this program in such a way that it should receive all content from the user and then it should send an email.

799

Answer

Solution:

What solved this issue for me was that some providers don't allow external recipients when using php mail:

Change the recipient ($recipient) in the code to a local recipient. This means use an email address from the server's domain, for example if your server domain is www.yourdomain.com then the recipient's email should be [email protected] Upload the modified php file and retry. If it's still not working: change the sender ($sender) to a local email (use the same email as used for recipient). Upload the modified php file and retry.

Hope this helps some! https://www.arclab.com/en/kb/php/how-to-test-and-fix-php-mail-function.html

289

Answer

Solution:

I had this problem and found that stripping back the headers helped me to get mail out. So this:

$headers  = "MIME-Version: 1.0;\r\n";
$headers .= "Content-type: text/plain; charset=utf-8;\r\n";
$headers .= "To: ".$recipient."\r\n";
$headers .= "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

became this:

$headers = "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

No need for the To: header.

Mail clients are pretty good at sniffing out URLs and rewriting them as a hyperlink. So I didn't bother writing HTML and specifying text/html in the content-type header. I just threw new lines with \r\n in the message body. I appreciate this isn't the coding purist's approach but it works for what I need it for.

952

Answer

Solution:

There are several possibilities:

  1. You're facing a server problem. The server does not have any mail server. So your mail is not working, because your code is fine and mail is working with type.

  2. You are not getting the posted value. Try your code with a static value.

  3. Use SMTP mails to send mail...

780

Answer

Solution:

Although there are portions of this answer that apply to only to the usage of themail() function itself, many of these troubleshooting steps can be applied to any PHP mailing system.

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.

error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");

See How can I get useful error messages in PHP?this answer for more details on this.

Make sure themail() function is called

It may seem silly but a common error is to forget to actually place themail() function in your code. Make sure it is there and not commented out.

Make sure themail() function is called correctly

bool mail ( string $to, string $subject, string $message [, string $additional_headers [, string $additional_parameters ]] )

The mail function takes three required parameters and optionally a fourth and fifth one. If your call tomail() does not have at least three parameters it will fail.

If your call tomail() does not have the correct parameters in the correct order it will also fail.

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 underlogs. Inside will be error messages the server reported, if any, related to your attempts to send emails.

Check for Port connection failure

Port block is a very common problem which most developers face while integrating their code to deliver emails using SMTP. And, this can be easily traced at the server maillogs (the location of server of mail log can vary from server to server, as explained above). In case you are on a shared hosting server, the ports 25 and 587 remain blocked by default. This block is been purposely done by your hosting provider. This is true even for some of the dedicated servers. When these ports are blocked, try to connect using port 2525. If you find that port is also blocked, then the only solution is to contact your hosting provider to unblock these ports.

Most of the hosting providers block these email ports to protect their network from sending any spam emails.

Use ports 25 or 587 for plain/TLS connections and port 465 for SSL connections. For most users, it is suggested to use port 587 to avoid rate limits set by some hosting providers.

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 right afterwards for concrete failures.

Check themail() return value

The function:

ReturnsTRUE 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 aFALSE 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 you receive aTRUE 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.

SoFALSE will help point you in the right direction whereasTRUE does not necessarily mean your email was sent successfully. This is important to note!

Make sure your hosting provider allows you to send emails and does not limit mail sending

Many shared webhosts, especially free webhosting providers, either do not allow emails to be sent from their servers or limit the amount that can be sent during any given time period. This is due to their efforts to limit spammers from taking advantage of their cheaper services.

If you think your host has emailing limits or blocks the sending of emails, check their FAQs to see if they list any such limitations. Otherwise, you may need to reach out to their support to verify if there are any restrictions in place around the sending of emails.

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" <[email protected]> ).
  • Monitor your abuse accounts, such as[email protected] and[email protected]. 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: [email protected]",
    "Reply-To: [email protected]",
    "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 [email protected]", // missing colon
    "Reply To: [email protected]",      // missing hyphen
    "X-Mailer: "PHP"/" . PHP_VERSION      // bad quotes
);

Don't use a fauxFrom: sender

While the mail must have a From: sender, you may not just use any value. In particular user-supplied sender addresses are a surefire way to get mails blocked:

$headers = array("From: $_POST[contactform_sender_email]"); // No!

Reason: your web or sending mail server is not SPF/DKIM-whitelisted to pretend being responsible for @hotmail or @gmail addresses. It may even silently drop mails withFrom: sender domains it's not configured for.

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 = '[email protected]';
// other variables ....
mail($recipient, $subject, $message, $headers); // $recipient should be $to

Another way to test this is to hard code the recipient value into themail() function call:

mail('[email protected]', $subject, $message, $headers);

This can apply to all of themail() 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 toPOST, make sure you are using$_POST to look for your form values. If you have set it toGET or didn't set it at all, make sure you use$_GET to look for your form values.

Make sure your formaction value points to the correct location

Make sure your formaction attribute contains a value that points to your PHP mailing code.

<form action="send_email.php" method="POST">

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 thelocalhost 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 custommail.log

In addition to your MTA's and PHP's log file, you can enable logging for the 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 http://php.net/manual/en/mail.configuration.php for details. (It's best to enable these options in thephp.ini or.user.ini or.htaccess perhaps.)

Check with a mail testing service

There are various delivery and spamminess checking services you can utilize to test your MTA/webserver setup. Typically you send a mail probe To: their address, then get a delivery report and more concrete failures or analyzations later:

Use a different mailer

PHP's built-inmail() 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:

All of which can be combined with a professional SMTP server/service provider. (Because typical 08/15 shared webhosting plans are hit or miss when it comes to email setup/configurability.)

885

Answer

Solution:

Add a mail header in the mail function:

$header = "From: [email protected]\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);

if($status)
{
    echo '<p>Your mail has been sent!</p>';
} else {
    echo '<p>Something went wrong. Please try again!</p>';
}
971

Answer

Solution:

  1. Always try sending headers in the mail function.
  2. If you are sending mail through localhost then do the SMTP settings for sending mail.
  3. If you are sending mail through a server then check the email sending feature is enabled on your server.
968

Answer

Solution:

If you are using an SMTP configuration for sending your email, try using PHPMailer instead. You can download the library from https://github.com/PHPMailer/PHPMailer.

I created my email sending this way:

function send_mail($email, $recipient_name, $message='')
{
    require("phpmailer/class.phpmailer.php");

    $mail = new PHPMailer();

    $mail->CharSet = "utf-8";
    $mail->IsSMTP();                                      // Set mailer to use SMTP
    $mail->Host = "mail.example.com";  // Specify main and backup server
    $mail->SMTPAuth = true;     // Turn on SMTP authentication
    $mail->Username = "myusername";  // SMTP username
    $mail->Password = "[email protected]"; // SMTP password

    $mail->From = "[email protected]";
    $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');
    $mail->addAttachment('files/file.xlsx');

    if(!$mail->Send())
    {
       echo "Message could not be sent. <p>";
       echo "Mailer Error: " . $mail->ErrorInfo;
       exit;
    }

    echo "Message has been sent";
}
412

Answer

Solution:

Just add some headers before sending mail:

<?php 
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com'; 
$to = '[email protected]'; 
$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: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

And one more thing. Themail() function is not working in localhost. Upload your code to a server and try.

643

Answer

Solution:

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('[email protected]', $subject, $message, $headers)

Use'' and not"".

This code works, but the email was received with half an hour lag.

93

Answer

Solution:

Mostly themail() function is disabled in shared hosting. A better option is to use SMTP. The best option would be Gmail or SendGrid.


SMTPconfig.php

<?php 
    $SmtpServer="smtp.*.*";
    $SmtpPort="2525"; //default
    $SmtpUser="***";
    $SmtpPass="***";
?>

SMTPmail.php

<?php
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;
        }
        else
        {
            $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");
            $talk["res"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpUser."\r\n");
            $talk["user"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpPass."\r\n");
            $talk["pass"]=fgets($SMTPIN,256);
            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");
            $talk["send"]=fgets($SMTPIN,256);
            //CLOSE CONNECTION AND EXIT ... 
            fputs ($SMTPIN, "QUIT\r\n"); 
            fclose($SMTPIN); 
            // 
        } 
        return $talk;
    } 
}
?>

contact_email.php

<?php 
include('SMTPconfig.php');
include('SMTPmail.php');
if($_SERVER["REQUEST_METHOD"] == "POST")
{
    $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();
}
?>
661

Answer

Solution:

If you only use themail()function, you need to complete the configuration file.

You need to open the mail expansion, and set theSMTP smtp_port and so on, and most important, your username and your password. Without that, mail cannot be sent. Also, you can use thePHPMail class to send.

206

Answer

Solution:

Try these two things separately and together:

  1. remove theif($_POST['submit']){}
  2. remove$from (just my gut)
43

Answer

Solution:

I think this should do the trick. I just added anif(isset and added concatenation to the variables in the body to separate PHP from HTML.

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: yoursite.com'; 
    $to = '[email protected]'; 
    $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>';
    } 
    else 
    { 
        echo '<p>Something went wrong, go back and try again!</p>'; 
    }
}

?>
132

Answer

Solution:

For anyone who finds this going forward, I would not recommend usingmail. There's some answers that touch on this, but not the why of it.

PHP'smail 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 frommail. 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 usemail to ultimately send the mail, but I would strongly recommend you not do that).

This means 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 callingisSMTP()), you can get a detailed transcript of the SMTP conversation using theSMTPDebug 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. Withmail 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).

383

Answer

Solution:

$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 class="page_speed_1833695416">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>";
}
985

Answer

Solution:

You can use config email by CodeIgniter. For example, using SMTP (simple way):

$config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'mail.domain.com', // Your SMTP host
        'smtp_port' => 26, // Default port for SMTP
        'smtp_user' => '[email protected]',
        'smtp_pass' => 'password',
        'mailtype' => 'html',
        'charset' => 'iso-8859-1',
        'wordwrap' => TRUE
);
$message = 'Your msg';
$this->load->library('email', $config);
$this->email->from('[email protected]', 'Title');
$this->email->to('[email protected]');
$this->email->subject('Header');
$this->email->message($message);

if($this->email->send()) 
{
   // Conditional true
}

It works for me!

796

Answer

Solution:

Try this

if ($_POST['submit']) {
    $success= mail($to, $subject, $body, $from);
    if($success)
    { 
        echo '
        <p>Your message has been sent!</p>
        ';
    } else { 
        echo '
        <p>Something went wrong, go back and try again!</p>
        '; 
    }
}
105

Answer

Solution:

Maybe the problem is the configuration of the mail server. To avoid this type of problems or you do not have to worry about the mail server problem, I recommend you use PHPMailer.

It is a plugin that has everything necessary to send mail, and the only thing you have to take into account is to have the SMTP port (Port: 25 and 465), enabled.

require_once 'PHPMailer/PHPMailer.php';
require_once '/servicios/PHPMailer/SMTP.php';
require_once '/servicios/PHPMailer/Exception.php';

$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
    //Server settings
    $mail->SMTPDebug = 0;
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = '[email protected]';
    $mail->Password = 'contrasenia';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;

    // Recipients
    $mail->setFrom('[email protected]', 'my name');
    $mail->addAddress('[email protected]');

    // Attachments
    $mail->addAttachment('optional file');         // Add files, is optional

    // Content
    $mail->isHTML(true);// Set email format to HTML
    $mail->Subject = utf8_decode("subject");
    $mail->Body    = utf8_decode("mail content");
    $mail->AltBody = '';
    $mail->send();
}
catch (Exception $e) {
    $error = $mail->ErrorInfo;
}
115

Answer

Solution:

First of all, you might have too many parameters for the mail() function... You are able to have of maximum of five,mail(to, subject, message, headers, parameters);

As far as the$from variable goes, that should automatically come from your webhost if your using the Linux cPanel. It automatically comes from your cPanel username and IP address.

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com';
$to = '[email protected]';
$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.

Themail($to, $subject, $message, etc.) in that order, or else there is a chance of it not working.

763

Answer

Solution:

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 www.AceITLab.com, 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.

134

Answer

Solution:

Make sure you have Sendmail installed in your server.

If you have checked your code and verified that there is nothing wrong there, go to /var/mail and check whether that folder is empty.

If it is empty, you will need to do a:

sudo apt-get install sendmail

if you are on an Ubuntu server.

514

Answer

Solution:

For those who do not want to use external mailers and want to mail() on a dedicated Linux server.

The way, how PHP mails, is described inphp.ini in section[mail function].

Parametersendmail-path describes how sendmail is called. The default value issendmail -t -i, so if you get a workingsendmail -t -i < message.txt in the Linux console - you will be done. You could also addmail.log to debug and be sure mail() is really called.

Different MTAs can implementsendmail. They just make a symbolic link to their binaries on that name. For example, in Debian the default is Postfix. Configure your MTA to send mail and test it from the console withsendmail -v -t -i < message.txt. Filemessage.txt should contain all headers of a message and a body, destination address for the envelope will be taken from theTo: header. Example:

From: [email protected]
To: [email protected]
Subject: Test mail via sendmail.

Text body.

I prefer to use ssmtp as MTA because it is simple and does not require running a daemon with opened ports. ssmtp fits only for sending mail from localhost. It also can send authenticated email via your account on a public mail service. Install ssmtp and edit configuration file/etc/ssmtp/ssmtp.conf. To be able also to receive local system mail to Unix accounts (alerts to root from cron jobs, for example) configure/etc/ssmtp/revaliases file.

Here is my configuration for my account on Yandex mail:

[email protected]
mailhub=smtp.yandex.ru:465
FromLineOverride=YES
UseTLS=YES
[email protected]
AuthPass=password
957

Answer

Solution:

Sendmail installation for Debian 10.0.0 ('Buster') was in fact trivial!

php.ini

[mail function]
sendmail_path=/usr/sbin/sendmail -t -i
; (Other directives are mostly windows)

Standard sendmail package install (allowing 'send'):

su -                                        # Install as user 'root'
dpkg --list                                 # Is install necessary?
apt-get install sendmail sendmail-cf m4     # Note multiple package selection
sendmailconfig                              # Respond all 'Y' for new install

Miscellaneous useful commands:

which sendmail                              # /usr/sbin/sendmail
which sendmailconfig                        # /usr/sbin/sendmailconfig
man sendmail                                # Documentation
systemctl restart sendmail                  # As and when required

Verification (of ability to send)

echo "Subject: sendmail test" | sendmail -v <yourEmail>@gmail.com

The above took about 5 minutes. Then I wasted 5 hours... Don't forget to check your spam folder!

763

Answer

Solution:

If you are running this code on a local server (i.e your computer for development purposes) it won't send the email to the recipient. It will create a.txt file in a folder namedmailoutput.

In the case if you are using a free hosing service, like000webhost orhostinger, those service providers disable themail() 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):

<?php
    $to      = '[email protected]';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: [email protected]' . "\r\n" .
        'Reply-To: [email protected]' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
?>
995

Answer

Solution:

You can use thePHPMailer and it works perfectly,here's a code example:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/phpmailer/phpmailer/src/Exception.php';
require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/phpmailer/src/SMTP.php';
$editor = $_POST["editor"];
$subject = $_POST["subject"];
$to = $_POST["to"];

try {

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->Mailer = "smtp";
        $mail->SMTPDebug  = 1;
        $mail->SMTPAuth   = TRUE;
        $mail->SMTPSecure = "tls";
        $mail->Port       = 587;
        $mail->Host       = "smtp.gmail.com";//using smtp server
        $mail->Username   = "[email protected]";//the email which will send the email 
        $mail->Password   = "XXXXXXXXXX";//the password

        $mail->IsHTML(true);
        $mail->AddAddress($to, "recipient-name");
        $mail->SetFrom("[email protected]", "from-name");
        $mail->AddReplyTo("[email protected]", "reply-to-name");
        $mail->Subject = $subject;
        $mail->MsgHTML($editor);




        if (!$mail->Send()) {
            echo "Error while sending Email.";
            var_dump($mail);
        } else {
            echo "Email sent successfully";
        }
    }
} catch (Exception $e) {
    echo $e->getMessage();
}
32

Answer

Solution:

You can see your errors by:

error_reporting(E_ALL);

And my sample code is:

<?php
    use PHPMailer\PHPMailer\PHPMailer;
    require 'PHPMailer.php';
    require 'SMTP.php';
    require 'Exception.php';

    $name = $_POST['name'];
    $mailid = $_POST['mail'];
    $mail = new PHPMailer;
    $mail->IsSMTP();
    $mail->SMTPDebug = 0;                   // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';         // Specify main and backup server
    $mail->Port = 587;                      // Set the SMTP port
    $mail->SMTPAuth = true;                 // Enable SMTP authentication
    $mail->Username = '[email protected]';  // SMTP username
    $mail->Password = 'password';           // SMTP password
    $mail->SMTPSecure = 'tls';              // Enable encryption, 'ssl' also accepted

    $mail->From = '[email protected]';
    $mail->FromName = 'name';
    $mail->AddAddress($mailid, $name);       // Name is optional
    $mail->IsHTML(true);                     // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'Here is your message' ;
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
    if (!$mail->Send()) {
       echo 'Message could not be sent.';
       echo 'Mailer Error: ' . $mail->ErrorInfo;
       exit;
    }
    echo 'Message has been sent';
?>
130

Answer

Solution:

If you're stuck with an app hosted on Hostgator, this is what solved my problem. Thanks a lot to the guy who posted the detailed solution. In case the link goes offline one day, there you have the summary:

  • Look for the sendmail path in your server. A simple way to check it, is to temporarily write the following code in a page which only you will access, to read the generated info:<?php phpinfo(); ?>. Open this page, and look forsendmail path. (Then, don't forget to remove this code!)
  • Problem and fix: if your sendmail path is saying only-t -i, then edit your server'sphp.ini and add the following line:sendmail_path = /usr/sbin/sendmail -t -i;

But, after being able to send mail with PHPmail() function, I learned that it sends not authenticated email, what created another issue. The emails were all falling in my Hotmail's junk mail box, and some emails were never delivered, which I guess is related to the fact that they are not authenticated. That's why I decided to switch frommail() toPHPMailer with SMTP, after all.

143

Answer

Solution:

It may be a problem with "From:" $email address in this part of the $headers:

From: \"$name\" <$email>

To try it out, send an email without the headers part, like:

mail('[email protected]', $subject, $message); 

If that is a case, try using an email account that is already created at the system you are trying to send mail from.

953

Answer

Solution:

<?php

$to       = '[email protected]';
$subject  = 'Write your email subject here.';
$message  = '
<html>
<head>
<title>Title here</title>
</head>
<body>
<p>Message here</p>
</body>
</html>
';

// Carriage return type (RFC).
$eol = "\r\n";

$headers  = "Reply-To: Name <[email protected]>".$eol;
$headers .= "Return-Path: Name <[email protected]>".$eol;
$headers .= "From: Name <[email protected]>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/html; charset=iso-8859-1".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;


mail($to, $subject, $message, $headers);

Sending HTML email While sending an email message you can specify a Mime version, content type and character set to send an HTML email.

Example The above example will send an HTML email message to [email protected] You can code this program in such a way that it should receive all content from the user and then it should send an email.

684

Answer

Solution:

What solved this issue for me was that some providers don't allow external recipients when using php mail:

Change the recipient ($recipient) in the code to a local recipient. This means use an email address from the server's domain, for example if your server domain is www.yourdomain.com then the recipient's email should be [email protected] Upload the modified php file and retry. If it's still not working: change the sender ($sender) to a local email (use the same email as used for recipient). Upload the modified php file and retry.

Hope this helps some! https://www.arclab.com/en/kb/php/how-to-test-and-fix-php-mail-function.html

876

Answer

Solution:

I had this problem and found that stripping back the headers helped me to get mail out. So this:

$headers  = "MIME-Version: 1.0;\r\n";
$headers .= "Content-type: text/plain; charset=utf-8;\r\n";
$headers .= "To: ".$recipient."\r\n";
$headers .= "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

became this:

$headers = "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

No need for the To: header.

Mail clients are pretty good at sniffing out URLs and rewriting them as a hyperlink. So I didn't bother writing HTML and specifying text/html in the content-type header. I just threw new lines with \r\n in the message body. I appreciate this isn't the coding purist's approach but it works for what I need it for.

497

Answer

Solution:

There are several possibilities:

  1. You're facing a server problem. The server does not have any mail server. So your mail is not working, because your code is fine and mail is working with type.

  2. You are not getting the posted value. Try your code with a static value.

  3. Use SMTP mails to send mail...

282

Answer

Solution:

Although there are portions of this answer that apply to only to the usage of themail() function itself, many of these troubleshooting steps can be applied to any PHP mailing system.

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.

error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");

See How can I get useful error messages in PHP?this answer for more details on this.

Make sure themail() function is called

It may seem silly but a common error is to forget to actually place themail() function in your code. Make sure it is there and not commented out.

Make sure themail() function is called correctly

bool mail ( string $to, string $subject, string $message [, string $additional_headers [, string $additional_parameters ]] )

The mail function takes three required parameters and optionally a fourth and fifth one. If your call tomail() does not have at least three parameters it will fail.

If your call tomail() does not have the correct parameters in the correct order it will also fail.

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 underlogs. Inside will be error messages the server reported, if any, related to your attempts to send emails.

Check for Port connection failure

Port block is a very common problem which most developers face while integrating their code to deliver emails using SMTP. And, this can be easily traced at the server maillogs (the location of server of mail log can vary from server to server, as explained above). In case you are on a shared hosting server, the ports 25 and 587 remain blocked by default. This block is been purposely done by your hosting provider. This is true even for some of the dedicated servers. When these ports are blocked, try to connect using port 2525. If you find that port is also blocked, then the only solution is to contact your hosting provider to unblock these ports.

Most of the hosting providers block these email ports to protect their network from sending any spam emails.

Use ports 25 or 587 for plain/TLS connections and port 465 for SSL connections. For most users, it is suggested to use port 587 to avoid rate limits set by some hosting providers.

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 right afterwards for concrete failures.

Check themail() return value

The function:

ReturnsTRUE 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 aFALSE 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 you receive aTRUE 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.

SoFALSE will help point you in the right direction whereasTRUE does not necessarily mean your email was sent successfully. This is important to note!

Make sure your hosting provider allows you to send emails and does not limit mail sending

Many shared webhosts, especially free webhosting providers, either do not allow emails to be sent from their servers or limit the amount that can be sent during any given time period. This is due to their efforts to limit spammers from taking advantage of their cheaper services.

If you think your host has emailing limits or blocks the sending of emails, check their FAQs to see if they list any such limitations. Otherwise, you may need to reach out to their support to verify if there are any restrictions in place around the sending of emails.

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" <[email protected]> ).
  • Monitor your abuse accounts, such as[email protected] and[email protected]. 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: [email protected]",
    "Reply-To: [email protected]",
    "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 [email protected]", // missing colon
    "Reply To: [email protected]",      // missing hyphen
    "X-Mailer: "PHP"/" . PHP_VERSION      // bad quotes
);

Don't use a fauxFrom: sender

While the mail must have a From: sender, you may not just use any value. In particular user-supplied sender addresses are a surefire way to get mails blocked:

$headers = array("From: $_POST[contactform_sender_email]"); // No!

Reason: your web or sending mail server is not SPF/DKIM-whitelisted to pretend being responsible for @hotmail or @gmail addresses. It may even silently drop mails withFrom: sender domains it's not configured for.

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 = '[email protected]';
// other variables ....
mail($recipient, $subject, $message, $headers); // $recipient should be $to

Another way to test this is to hard code the recipient value into themail() function call:

mail('[email protected]', $subject, $message, $headers);

This can apply to all of themail() 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 toPOST, make sure you are using$_POST to look for your form values. If you have set it toGET or didn't set it at all, make sure you use$_GET to look for your form values.

Make sure your formaction value points to the correct location

Make sure your formaction attribute contains a value that points to your PHP mailing code.

<form action="send_email.php" method="POST">

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 thelocalhost 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 custommail.log

In addition to your MTA's and PHP's log file, you can enable logging for the 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 http://php.net/manual/en/mail.configuration.php for details. (It's best to enable these options in thephp.ini or.user.ini or.htaccess perhaps.)

Check with a mail testing service

There are various delivery and spamminess checking services you can utilize to test your MTA/webserver setup. Typically you send a mail probe To: their address, then get a delivery report and more concrete failures or analyzations later:

Use a different mailer

PHP's built-inmail() 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:

All of which can be combined with a professional SMTP server/service provider. (Because typical 08/15 shared webhosting plans are hit or miss when it comes to email setup/configurability.)

987

Answer

Solution:

Add a mail header in the mail function:

$header = "From: [email protected]\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);

if($status)
{
    echo '<p>Your mail has been sent!</p>';
} else {
    echo '<p>Something went wrong. Please try again!</p>';
}
820

Answer

Solution:

  1. Always try sending headers in the mail function.
  2. If you are sending mail through localhost then do the SMTP settings for sending mail.
  3. If you are sending mail through a server then check the email sending feature is enabled on your server.
965

Answer

Solution:

If you are using an SMTP configuration for sending your email, try using PHPMailer instead. You can download the library from https://github.com/PHPMailer/PHPMailer.

I created my email sending this way:

function send_mail($email, $recipient_name, $message='')
{
    require("phpmailer/class.phpmailer.php");

    $mail = new PHPMailer();

    $mail->CharSet = "utf-8";
    $mail->IsSMTP();                                      // Set mailer to use SMTP
    $mail->Host = "mail.example.com";  // Specify main and backup server
    $mail->SMTPAuth = true;     // Turn on SMTP authentication
    $mail->Username = "myusername";  // SMTP username
    $mail->Password = "[email protected]"; // SMTP password

    $mail->From = "[email protected]";
    $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');
    $mail->addAttachment('files/file.xlsx');

    if(!$mail->Send())
    {
       echo "Message could not be sent. <p>";
       echo "Mailer Error: " . $mail->ErrorInfo;
       exit;
    }

    echo "Message has been sent";
}
956

Answer

Solution:

Just add some headers before sending mail:

<?php 
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com'; 
$to = '[email protected]'; 
$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: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

And one more thing. Themail() function is not working in localhost. Upload your code to a server and try.

154

Answer

Solution:

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('[email protected]', $subject, $message, $headers)

Use'' and not"".

This code works, but the email was received with half an hour lag.

268

Answer

Solution:

Mostly themail() function is disabled in shared hosting. A better option is to use SMTP. The best option would be Gmail or SendGrid.


SMTPconfig.php

<?php 
    $SmtpServer="smtp.*.*";
    $SmtpPort="2525"; //default
    $SmtpUser="***";
    $SmtpPass="***";
?>

SMTPmail.php

<?php
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;
        }
        else
        {
            $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");
            $talk["res"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpUser."\r\n");
            $talk["user"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpPass."\r\n");
            $talk["pass"]=fgets($SMTPIN,256);
            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");
            $talk["send"]=fgets($SMTPIN,256);
            //CLOSE CONNECTION AND EXIT ... 
            fputs ($SMTPIN, "QUIT\r\n"); 
            fclose($SMTPIN); 
            // 
        } 
        return $talk;
    } 
}
?>

contact_email.php

<?php 
include('SMTPconfig.php');
include('SMTPmail.php');
if($_SERVER["REQUEST_METHOD"] == "POST")
{
    $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();
}
?>
405

Answer

Solution:

If you only use themail()function, you need to complete the configuration file.

You need to open the mail expansion, and set theSMTP smtp_port and so on, and most important, your username and your password. Without that, mail cannot be sent. Also, you can use thePHPMail class to send.

777

Answer

Solution:

Try these two things separately and together:

  1. remove theif($_POST['submit']){}
  2. remove$from (just my gut)
990

Answer

Solution:

I think this should do the trick. I just added anif(isset and added concatenation to the variables in the body to separate PHP from HTML.

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: yoursite.com'; 
    $to = '[email protected]'; 
    $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>';
    } 
    else 
    { 
        echo '<p>Something went wrong, go back and try again!</p>'; 
    }
}

?>
822

Answer

Solution:

For anyone who finds this going forward, I would not recommend usingmail. There's some answers that touch on this, but not the why of it.

PHP'smail 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 frommail. 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 usemail to ultimately send the mail, but I would strongly recommend you not do that).

This means 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 callingisSMTP()), you can get a detailed transcript of the SMTP conversation using theSMTPDebug 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. Withmail 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).

242

Answer

Solution:

$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 class="page_speed_1833695416">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>";
}
348

Answer

Solution:

You can use config email by CodeIgniter. For example, using SMTP (simple way):

$config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'mail.domain.com', // Your SMTP host
        'smtp_port' => 26, // Default port for SMTP
        'smtp_user' => '[email protected]',
        'smtp_pass' => 'password',
        'mailtype' => 'html',
        'charset' => 'iso-8859-1',
        'wordwrap' => TRUE
);
$message = 'Your msg';
$this->load->library('email', $config);
$this->email->from('[email protected]', 'Title');
$this->email->to('[email protected]');
$this->email->subject('Header');
$this->email->message($message);

if($this->email->send()) 
{
   // Conditional true
}

It works for me!

835

Answer

Solution:

Try this

if ($_POST['submit']) {
    $success= mail($to, $subject, $body, $from);
    if($success)
    { 
        echo '
        <p>Your message has been sent!</p>
        ';
    } else { 
        echo '
        <p>Something went wrong, go back and try again!</p>
        '; 
    }
}
963

Answer

Solution:

Maybe the problem is the configuration of the mail server. To avoid this type of problems or you do not have to worry about the mail server problem, I recommend you use PHPMailer.

It is a plugin that has everything necessary to send mail, and the only thing you have to take into account is to have the SMTP port (Port: 25 and 465), enabled.

require_once 'PHPMailer/PHPMailer.php';
require_once '/servicios/PHPMailer/SMTP.php';
require_once '/servicios/PHPMailer/Exception.php';

$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
    //Server settings
    $mail->SMTPDebug = 0;
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = '[email protected]';
    $mail->Password = 'contrasenia';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;

    // Recipients
    $mail->setFrom('[email protected]', 'my name');
    $mail->addAddress('[email protected]');

    // Attachments
    $mail->addAttachment('optional file');         // Add files, is optional

    // Content
    $mail->isHTML(true);// Set email format to HTML
    $mail->Subject = utf8_decode("subject");
    $mail->Body    = utf8_decode("mail content");
    $mail->AltBody = '';
    $mail->send();
}
catch (Exception $e) {
    $error = $mail->ErrorInfo;
}
717

Answer

Solution:

First of all, you might have too many parameters for the mail() function... You are able to have of maximum of five,mail(to, subject, message, headers, parameters);

As far as the$from variable goes, that should automatically come from your webhost if your using the Linux cPanel. It automatically comes from your cPanel username and IP address.

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com';
$to = '[email protected]';
$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.

Themail($to, $subject, $message, etc.) in that order, or else there is a chance of it not working.

236

Answer

Solution:

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 www.AceITLab.com, 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.

979

Answer

Solution:

Make sure you have Sendmail installed in your server.

If you have checked your code and verified that there is nothing wrong there, go to /var/mail and check whether that folder is empty.

If it is empty, you will need to do a:

sudo apt-get install sendmail

if you are on an Ubuntu server.

856

Answer

Solution:

For those who do not want to use external mailers and want to mail() on a dedicated Linux server.

The way, how PHP mails, is described inphp.ini in section[mail function].

Parametersendmail-path describes how sendmail is called. The default value issendmail -t -i, so if you get a workingsendmail -t -i < message.txt in the Linux console - you will be done. You could also addmail.log to debug and be sure mail() is really called.

Different MTAs can implementsendmail. They just make a symbolic link to their binaries on that name. For example, in Debian the default is Postfix. Configure your MTA to send mail and test it from the console withsendmail -v -t -i < message.txt. Filemessage.txt should contain all headers of a message and a body, destination address for the envelope will be taken from theTo: header. Example:

From: [email protected]
To: [email protected]
Subject: Test mail via sendmail.

Text body.

I prefer to use ssmtp as MTA because it is simple and does not require running a daemon with opened ports. ssmtp fits only for sending mail from localhost. It also can send authenticated email via your account on a public mail service. Install ssmtp and edit configuration file/etc/ssmtp/ssmtp.conf. To be able also to receive local system mail to Unix accounts (alerts to root from cron jobs, for example) configure/etc/ssmtp/revaliases file.

Here is my configuration for my account on Yandex mail:

[email protected]
mailhub=smtp.yandex.ru:465
FromLineOverride=YES
UseTLS=YES
[email protected]
AuthPass=password
547

Answer

Solution:

Sendmail installation for Debian 10.0.0 ('Buster') was in fact trivial!

php.ini

[mail function]
sendmail_path=/usr/sbin/sendmail -t -i
; (Other directives are mostly windows)

Standard sendmail package install (allowing 'send'):

su -                                        # Install as user 'root'
dpkg --list                                 # Is install necessary?
apt-get install sendmail sendmail-cf m4     # Note multiple package selection
sendmailconfig                              # Respond all 'Y' for new install

Miscellaneous useful commands:

which sendmail                              # /usr/sbin/sendmail
which sendmailconfig                        # /usr/sbin/sendmailconfig
man sendmail                                # Documentation
systemctl restart sendmail                  # As and when required

Verification (of ability to send)

echo "Subject: sendmail test" | sendmail -v <yourEmail>@gmail.com

The above took about 5 minutes. Then I wasted 5 hours... Don't forget to check your spam folder!

803

Answer

Solution:

If you are running this code on a local server (i.e your computer for development purposes) it won't send the email to the recipient. It will create a.txt file in a folder namedmailoutput.

In the case if you are using a free hosing service, like000webhost orhostinger, those service providers disable themail() 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):

<?php
    $to      = '[email protected]';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: [email protected]' . "\r\n" .
        'Reply-To: [email protected]' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
?>
75

Answer

Solution:

You can use thePHPMailer and it works perfectly,here's a code example:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/phpmailer/phpmailer/src/Exception.php';
require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/phpmailer/src/SMTP.php';
$editor = $_POST["editor"];
$subject = $_POST["subject"];
$to = $_POST["to"];

try {

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->Mailer = "smtp";
        $mail->SMTPDebug  = 1;
        $mail->SMTPAuth   = TRUE;
        $mail->SMTPSecure = "tls";
        $mail->Port       = 587;
        $mail->Host       = "smtp.gmail.com";//using smtp server
        $mail->Username   = "[email protected]";//the email which will send the email 
        $mail->Password   = "XXXXXXXXXX";//the password

        $mail->IsHTML(true);
        $mail->AddAddress($to, "recipient-name");
        $mail->SetFrom("[email protected]", "from-name");
        $mail->AddReplyTo("[email protected]", "reply-to-name");
        $mail->Subject = $subject;
        $mail->MsgHTML($editor);




        if (!$mail->Send()) {
            echo "Error while sending Email.";
            var_dump($mail);
        } else {
            echo "Email sent successfully";
        }
    }
} catch (Exception $e) {
    echo $e->getMessage();
}
857

Answer

Solution:

You can see your errors by:

error_reporting(E_ALL);

And my sample code is:

<?php
    use PHPMailer\PHPMailer\PHPMailer;
    require 'PHPMailer.php';
    require 'SMTP.php';
    require 'Exception.php';

    $name = $_POST['name'];
    $mailid = $_POST['mail'];
    $mail = new PHPMailer;
    $mail->IsSMTP();
    $mail->SMTPDebug = 0;                   // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';         // Specify main and backup server
    $mail->Port = 587;                      // Set the SMTP port
    $mail->SMTPAuth = true;                 // Enable SMTP authentication
    $mail->Username = '[email protected]';  // SMTP username
    $mail->Password = 'password';           // SMTP password
    $mail->SMTPSecure = 'tls';              // Enable encryption, 'ssl' also accepted

    $mail->From = '[email protected]';
    $mail->FromName = 'name';
    $mail->AddAddress($mailid, $name);       // Name is optional
    $mail->IsHTML(true);                     // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'Here is your message' ;
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
    if (!$mail->Send()) {
       echo 'Message could not be sent.';
       echo 'Mailer Error: ' . $mail->ErrorInfo;
       exit;
    }
    echo 'Message has been sent';
?>
400

Answer

Solution:

If you're stuck with an app hosted on Hostgator, this is what solved my problem. Thanks a lot to the guy who posted the detailed solution. In case the link goes offline one day, there you have the summary:

  • Look for the sendmail path in your server. A simple way to check it, is to temporarily write the following code in a page which only you will access, to read the generated info:<?php phpinfo(); ?>. Open this page, and look forsendmail path. (Then, don't forget to remove this code!)
  • Problem and fix: if your sendmail path is saying only-t -i, then edit your server'sphp.ini and add the following line:sendmail_path = /usr/sbin/sendmail -t -i;

But, after being able to send mail with PHPmail() function, I learned that it sends not authenticated email, what created another issue. The emails were all falling in my Hotmail's junk mail box, and some emails were never delivered, which I guess is related to the fact that they are not authenticated. That's why I decided to switch frommail() toPHPMailer with SMTP, after all.

204

Answer

Solution:

It may be a problem with "From:" $email address in this part of the $headers:

From: \"$name\" <$email>

To try it out, send an email without the headers part, like:

mail('[email protected]', $subject, $message); 

If that is a case, try using an email account that is already created at the system you are trying to send mail from.

509

Answer

Solution:

<?php

$to       = '[email protected]';
$subject  = 'Write your email subject here.';
$message  = '
<html>
<head>
<title>Title here</title>
</head>
<body>
<p>Message here</p>
</body>
</html>
';

// Carriage return type (RFC).
$eol = "\r\n";

$headers  = "Reply-To: Name <[email protected]>".$eol;
$headers .= "Return-Path: Name <[email protected]>".$eol;
$headers .= "From: Name <[email protected]>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/html; charset=iso-8859-1".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;


mail($to, $subject, $message, $headers);

Sending HTML email While sending an email message you can specify a Mime version, content type and character set to send an HTML email.

Example The above example will send an HTML email message to [email protected] You can code this program in such a way that it should receive all content from the user and then it should send an email.

256

Answer

Solution:

What solved this issue for me was that some providers don't allow external recipients when using php mail:

Change the recipient ($recipient) in the code to a local recipient. This means use an email address from the server's domain, for example if your server domain is www.yourdomain.com then the recipient's email should be [email protected] Upload the modified php file and retry. If it's still not working: change the sender ($sender) to a local email (use the same email as used for recipient). Upload the modified php file and retry.

Hope this helps some! https://www.arclab.com/en/kb/php/how-to-test-and-fix-php-mail-function.html

544

Answer

Solution:

I had this problem and found that stripping back the headers helped me to get mail out. So this:

$headers  = "MIME-Version: 1.0;\r\n";
$headers .= "Content-type: text/plain; charset=utf-8;\r\n";
$headers .= "To: ".$recipient."\r\n";
$headers .= "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

became this:

$headers = "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

No need for the To: header.

Mail clients are pretty good at sniffing out URLs and rewriting them as a hyperlink. So I didn't bother writing HTML and specifying text/html in the content-type header. I just threw new lines with \r\n in the message body. I appreciate this isn't the coding purist's approach but it works for what I need it for.

972

Answer

Solution:

There are several possibilities:

  1. You're facing a server problem. The server does not have any mail server. So your mail is not working, because your code is fine and mail is working with type.

  2. You are not getting the posted value. Try your code with a static value.

  3. Use SMTP mails to send mail...

483

Answer

Solution:

Although there are portions of this answer that apply to only to the usage of themail() function itself, many of these troubleshooting steps can be applied to any PHP mailing system.

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.

error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");

See How can I get useful error messages in PHP?this answer for more details on this.

Make sure themail() function is called

It may seem silly but a common error is to forget to actually place themail() function in your code. Make sure it is there and not commented out.

Make sure themail() function is called correctly

bool mail ( string $to, string $subject, string $message [, string $additional_headers [, string $additional_parameters ]] )

The mail function takes three required parameters and optionally a fourth and fifth one. If your call tomail() does not have at least three parameters it will fail.

If your call tomail() does not have the correct parameters in the correct order it will also fail.

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 underlogs. Inside will be error messages the server reported, if any, related to your attempts to send emails.

Check for Port connection failure

Port block is a very common problem which most developers face while integrating their code to deliver emails using SMTP. And, this can be easily traced at the server maillogs (the location of server of mail log can vary from server to server, as explained above). In case you are on a shared hosting server, the ports 25 and 587 remain blocked by default. This block is been purposely done by your hosting provider. This is true even for some of the dedicated servers. When these ports are blocked, try to connect using port 2525. If you find that port is also blocked, then the only solution is to contact your hosting provider to unblock these ports.

Most of the hosting providers block these email ports to protect their network from sending any spam emails.

Use ports 25 or 587 for plain/TLS connections and port 465 for SSL connections. For most users, it is suggested to use port 587 to avoid rate limits set by some hosting providers.

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 right afterwards for concrete failures.

Check themail() return value

The function:

ReturnsTRUE 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 aFALSE 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 you receive aTRUE 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.

SoFALSE will help point you in the right direction whereasTRUE does not necessarily mean your email was sent successfully. This is important to note!

Make sure your hosting provider allows you to send emails and does not limit mail sending

Many shared webhosts, especially free webhosting providers, either do not allow emails to be sent from their servers or limit the amount that can be sent during any given time period. This is due to their efforts to limit spammers from taking advantage of their cheaper services.

If you think your host has emailing limits or blocks the sending of emails, check their FAQs to see if they list any such limitations. Otherwise, you may need to reach out to their support to verify if there are any restrictions in place around the sending of emails.

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" <[email protected]> ).
  • Monitor your abuse accounts, such as[email protected] and[email protected]. 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: [email protected]",
    "Reply-To: [email protected]",
    "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 [email protected]", // missing colon
    "Reply To: [email protected]",      // missing hyphen
    "X-Mailer: "PHP"/" . PHP_VERSION      // bad quotes
);

Don't use a fauxFrom: sender

While the mail must have a From: sender, you may not just use any value. In particular user-supplied sender addresses are a surefire way to get mails blocked:

$headers = array("From: $_POST[contactform_sender_email]"); // No!

Reason: your web or sending mail server is not SPF/DKIM-whitelisted to pretend being responsible for @hotmail or @gmail addresses. It may even silently drop mails withFrom: sender domains it's not configured for.

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 = '[email protected]';
// other variables ....
mail($recipient, $subject, $message, $headers); // $recipient should be $to

Another way to test this is to hard code the recipient value into themail() function call:

mail('[email protected]', $subject, $message, $headers);

This can apply to all of themail() 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 toPOST, make sure you are using$_POST to look for your form values. If you have set it toGET or didn't set it at all, make sure you use$_GET to look for your form values.

Make sure your formaction value points to the correct location

Make sure your formaction attribute contains a value that points to your PHP mailing code.

<form action="send_email.php" method="POST">

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 thelocalhost 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 custommail.log

In addition to your MTA's and PHP's log file, you can enable logging for the 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 http://php.net/manual/en/mail.configuration.php for details. (It's best to enable these options in thephp.ini or.user.ini or.htaccess perhaps.)

Check with a mail testing service

There are various delivery and spamminess checking services you can utilize to test your MTA/webserver setup. Typically you send a mail probe To: their address, then get a delivery report and more concrete failures or analyzations later:

Use a different mailer

PHP's built-inmail() 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:

All of which can be combined with a professional SMTP server/service provider. (Because typical 08/15 shared webhosting plans are hit or miss when it comes to email setup/configurability.)

969

Answer

Solution:

Add a mail header in the mail function:

$header = "From: [email protected]\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);

if($status)
{
    echo '<p>Your mail has been sent!</p>';
} else {
    echo '<p>Something went wrong. Please try again!</p>';
}
235

Answer

Solution:

  1. Always try sending headers in the mail function.
  2. If you are sending mail through localhost then do the SMTP settings for sending mail.
  3. If you are sending mail through a server then check the email sending feature is enabled on your server.
181

Answer

Solution:

If you are using an SMTP configuration for sending your email, try using PHPMailer instead. You can download the library from https://github.com/PHPMailer/PHPMailer.

I created my email sending this way:

function send_mail($email, $recipient_name, $message='')
{
    require("phpmailer/class.phpmailer.php");

    $mail = new PHPMailer();

    $mail->CharSet = "utf-8";
    $mail->IsSMTP();                                      // Set mailer to use SMTP
    $mail->Host = "mail.example.com";  // Specify main and backup server
    $mail->SMTPAuth = true;     // Turn on SMTP authentication
    $mail->Username = "myusername";  // SMTP username
    $mail->Password = "[email protected]"; // SMTP password

    $mail->From = "[email protected]";
    $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');
    $mail->addAttachment('files/file.xlsx');

    if(!$mail->Send())
    {
       echo "Message could not be sent. <p>";
       echo "Mailer Error: " . $mail->ErrorInfo;
       exit;
    }

    echo "Message has been sent";
}
726

Answer

Solution:

Just add some headers before sending mail:

<?php 
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com'; 
$to = '[email protected]'; 
$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: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

And one more thing. Themail() function is not working in localhost. Upload your code to a server and try.

737

Answer

Solution:

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('[email protected]', $subject, $message, $headers)

Use'' and not"".

This code works, but the email was received with half an hour lag.

660

Answer

Solution:

Mostly themail() function is disabled in shared hosting. A better option is to use SMTP. The best option would be Gmail or SendGrid.


SMTPconfig.php

<?php 
    $SmtpServer="smtp.*.*";
    $SmtpPort="2525"; //default
    $SmtpUser="***";
    $SmtpPass="***";
?>

SMTPmail.php

<?php
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;
        }
        else
        {
            $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");
            $talk["res"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpUser."\r\n");
            $talk["user"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpPass."\r\n");
            $talk["pass"]=fgets($SMTPIN,256);
            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");
            $talk["send"]=fgets($SMTPIN,256);
            //CLOSE CONNECTION AND EXIT ... 
            fputs ($SMTPIN, "QUIT\r\n"); 
            fclose($SMTPIN); 
            // 
        } 
        return $talk;
    } 
}
?>

contact_email.php

<?php 
include('SMTPconfig.php');
include('SMTPmail.php');
if($_SERVER["REQUEST_METHOD"] == "POST")
{
    $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();
}
?>
874

Answer

Solution:

If you only use themail()function, you need to complete the configuration file.

You need to open the mail expansion, and set theSMTP smtp_port and so on, and most important, your username and your password. Without that, mail cannot be sent. Also, you can use thePHPMail class to send.

440

Answer

Solution:

Try these two things separately and together:

  1. remove theif($_POST['submit']){}
  2. remove$from (just my gut)
466

Answer

Solution:

I think this should do the trick. I just added anif(isset and added concatenation to the variables in the body to separate PHP from HTML.

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: yoursite.com'; 
    $to = '[email protected]'; 
    $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>';
    } 
    else 
    { 
        echo '<p>Something went wrong, go back and try again!</p>'; 
    }
}

?>
653

Answer

Solution:

For anyone who finds this going forward, I would not recommend usingmail. There's some answers that touch on this, but not the why of it.

PHP'smail 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 frommail. 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 usemail to ultimately send the mail, but I would strongly recommend you not do that).

This means 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 callingisSMTP()), you can get a detailed transcript of the SMTP conversation using theSMTPDebug 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. Withmail 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).

377

Answer

Solution:

$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 class="page_speed_1833695416">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>";
}
461

Answer

Solution:

You can use config email by CodeIgniter. For example, using SMTP (simple way):

$config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'mail.domain.com', // Your SMTP host
        'smtp_port' => 26, // Default port for SMTP
        'smtp_user' => '[email protected]',
        'smtp_pass' => 'password',
        'mailtype' => 'html',
        'charset' => 'iso-8859-1',
        'wordwrap' => TRUE
);
$message = 'Your msg';
$this->load->library('email', $config);
$this->email->from('[email protected]', 'Title');
$this->email->to('[email protected]');
$this->email->subject('Header');
$this->email->message($message);

if($this->email->send()) 
{
   // Conditional true
}

It works for me!

266

Answer

Solution:

Try this

if ($_POST['submit']) {
    $success= mail($to, $subject, $body, $from);
    if($success)
    { 
        echo '
        <p>Your message has been sent!</p>
        ';
    } else { 
        echo '
        <p>Something went wrong, go back and try again!</p>
        '; 
    }
}
24

Answer

Solution:

Maybe the problem is the configuration of the mail server. To avoid this type of problems or you do not have to worry about the mail server problem, I recommend you use PHPMailer.

It is a plugin that has everything necessary to send mail, and the only thing you have to take into account is to have the SMTP port (Port: 25 and 465), enabled.

require_once 'PHPMailer/PHPMailer.php';
require_once '/servicios/PHPMailer/SMTP.php';
require_once '/servicios/PHPMailer/Exception.php';

$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
    //Server settings
    $mail->SMTPDebug = 0;
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = '[email protected]';
    $mail->Password = 'contrasenia';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;

    // Recipients
    $mail->setFrom('[email protected]', 'my name');
    $mail->addAddress('[email protected]');

    // Attachments
    $mail->addAttachment('optional file');         // Add files, is optional

    // Content
    $mail->isHTML(true);// Set email format to HTML
    $mail->Subject = utf8_decode("subject");
    $mail->Body    = utf8_decode("mail content");
    $mail->AltBody = '';
    $mail->send();
}
catch (Exception $e) {
    $error = $mail->ErrorInfo;
}
262

Answer

Solution:

First of all, you might have too many parameters for the mail() function... You are able to have of maximum of five,mail(to, subject, message, headers, parameters);

As far as the$from variable goes, that should automatically come from your webhost if your using the Linux cPanel. It automatically comes from your cPanel username and IP address.

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com';
$to = '[email protected]';
$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.

Themail($to, $subject, $message, etc.) in that order, or else there is a chance of it not working.

345

Answer

Solution:

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 www.AceITLab.com, 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.

74

Answer

Solution:

Make sure you have Sendmail installed in your server.

If you have checked your code and verified that there is nothing wrong there, go to /var/mail and check whether that folder is empty.

If it is empty, you will need to do a:

sudo apt-get install sendmail

if you are on an Ubuntu server.

469

Answer

Solution:

For those who do not want to use external mailers and want to mail() on a dedicated Linux server.

The way, how PHP mails, is described inphp.ini in section[mail function].

Parametersendmail-path describes how sendmail is called. The default value issendmail -t -i, so if you get a workingsendmail -t -i < message.txt in the Linux console - you will be done. You could also addmail.log to debug and be sure mail() is really called.

Different MTAs can implementsendmail. They just make a symbolic link to their binaries on that name. For example, in Debian the default is Postfix. Configure your MTA to send mail and test it from the console withsendmail -v -t -i < message.txt. Filemessage.txt should contain all headers of a message and a body, destination address for the envelope will be taken from theTo: header. Example:

From: [email protected]
To: [email protected]
Subject: Test mail via sendmail.

Text body.

I prefer to use ssmtp as MTA because it is simple and does not require running a daemon with opened ports. ssmtp fits only for sending mail from localhost. It also can send authenticated email via your account on a public mail service. Install ssmtp and edit configuration file/etc/ssmtp/ssmtp.conf. To be able also to receive local system mail to Unix accounts (alerts to root from cron jobs, for example) configure/etc/ssmtp/revaliases file.

Here is my configuration for my account on Yandex mail:

[email protected]
mailhub=smtp.yandex.ru:465
FromLineOverride=YES
UseTLS=YES
[email protected]
AuthPass=password
176

Answer

Solution:

Sendmail installation for Debian 10.0.0 ('Buster') was in fact trivial!

php.ini

[mail function]
sendmail_path=/usr/sbin/sendmail -t -i
; (Other directives are mostly windows)

Standard sendmail package install (allowing 'send'):

su -                                        # Install as user 'root'
dpkg --list                                 # Is install necessary?
apt-get install sendmail sendmail-cf m4     # Note multiple package selection
sendmailconfig                              # Respond all 'Y' for new install

Miscellaneous useful commands:

which sendmail                              # /usr/sbin/sendmail
which sendmailconfig                        # /usr/sbin/sendmailconfig
man sendmail                                # Documentation
systemctl restart sendmail                  # As and when required

Verification (of ability to send)

echo "Subject: sendmail test" | sendmail -v <yourEmail>@gmail.com

The above took about 5 minutes. Then I wasted 5 hours... Don't forget to check your spam folder!

948

Answer

Solution:

If you are running this code on a local server (i.e your computer for development purposes) it won't send the email to the recipient. It will create a.txt file in a folder namedmailoutput.

In the case if you are using a free hosing service, like000webhost orhostinger, those service providers disable themail() 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):

<?php
    $to      = '[email protected]';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: [email protected]' . "\r\n" .
        'Reply-To: [email protected]' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
?>
651

Answer

Solution:

You can use thePHPMailer and it works perfectly,here's a code example:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/phpmailer/phpmailer/src/Exception.php';
require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/phpmailer/src/SMTP.php';
$editor = $_POST["editor"];
$subject = $_POST["subject"];
$to = $_POST["to"];

try {

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->Mailer = "smtp";
        $mail->SMTPDebug  = 1;
        $mail->SMTPAuth   = TRUE;
        $mail->SMTPSecure = "tls";
        $mail->Port       = 587;
        $mail->Host       = "smtp.gmail.com";//using smtp server
        $mail->Username   = "[email protected]";//the email which will send the email 
        $mail->Password   = "XXXXXXXXXX";//the password

        $mail->IsHTML(true);
        $mail->AddAddress($to, "recipient-name");
        $mail->SetFrom("[email protected]", "from-name");
        $mail->AddReplyTo("[email protected]", "reply-to-name");
        $mail->Subject = $subject;
        $mail->MsgHTML($editor);




        if (!$mail->Send()) {
            echo "Error while sending Email.";
            var_dump($mail);
        } else {
            echo "Email sent successfully";
        }
    }
} catch (Exception $e) {
    echo $e->getMessage();
}
606

Answer

Solution:

You can see your errors by:

error_reporting(E_ALL);

And my sample code is:

<?php
    use PHPMailer\PHPMailer\PHPMailer;
    require 'PHPMailer.php';
    require 'SMTP.php';
    require 'Exception.php';

    $name = $_POST['name'];
    $mailid = $_POST['mail'];
    $mail = new PHPMailer;
    $mail->IsSMTP();
    $mail->SMTPDebug = 0;                   // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';         // Specify main and backup server
    $mail->Port = 587;                      // Set the SMTP port
    $mail->SMTPAuth = true;                 // Enable SMTP authentication
    $mail->Username = '[email protected]';  // SMTP username
    $mail->Password = 'password';           // SMTP password
    $mail->SMTPSecure = 'tls';              // Enable encryption, 'ssl' also accepted

    $mail->From = '[email protected]';
    $mail->FromName = 'name';
    $mail->AddAddress($mailid, $name);       // Name is optional
    $mail->IsHTML(true);                     // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'Here is your message' ;
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
    if (!$mail->Send()) {
       echo 'Message could not be sent.';
       echo 'Mailer Error: ' . $mail->ErrorInfo;
       exit;
    }
    echo 'Message has been sent';
?>
139

Answer

Solution:

If you're stuck with an app hosted on Hostgator, this is what solved my problem. Thanks a lot to the guy who posted the detailed solution. In case the link goes offline one day, there you have the summary:

  • Look for the sendmail path in your server. A simple way to check it, is to temporarily write the following code in a page which only you will access, to read the generated info:<?php phpinfo(); ?>. Open this page, and look forsendmail path. (Then, don't forget to remove this code!)
  • Problem and fix: if your sendmail path is saying only-t -i, then edit your server'sphp.ini and add the following line:sendmail_path = /usr/sbin/sendmail -t -i;

But, after being able to send mail with PHPmail() function, I learned that it sends not authenticated email, what created another issue. The emails were all falling in my Hotmail's junk mail box, and some emails were never delivered, which I guess is related to the fact that they are not authenticated. That's why I decided to switch frommail() toPHPMailer with SMTP, after all.

620

Answer

Solution:

It may be a problem with "From:" $email address in this part of the $headers:

From: \"$name\" <$email>

To try it out, send an email without the headers part, like:

mail('[email protected]', $subject, $message); 

If that is a case, try using an email account that is already created at the system you are trying to send mail from.

827

Answer

Solution:

<?php

$to       = '[email protected]';
$subject  = 'Write your email subject here.';
$message  = '
<html>
<head>
<title>Title here</title>
</head>
<body>
<p>Message here</p>
</body>
</html>
';

// Carriage return type (RFC).
$eol = "\r\n";

$headers  = "Reply-To: Name <[email protected]>".$eol;
$headers .= "Return-Path: Name <[email protected]>".$eol;
$headers .= "From: Name <[email protected]>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/html; charset=iso-8859-1".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;


mail($to, $subject, $message, $headers);

Sending HTML email While sending an email message you can specify a Mime version, content type and character set to send an HTML email.

Example The above example will send an HTML email message to [email protected] You can code this program in such a way that it should receive all content from the user and then it should send an email.

580

Answer

Solution:

What solved this issue for me was that some providers don't allow external recipients when using php mail:

Change the recipient ($recipient) in the code to a local recipient. This means use an email address from the server's domain, for example if your server domain is www.yourdomain.com then the recipient's email should be [email protected] Upload the modified php file and retry. If it's still not working: change the sender ($sender) to a local email (use the same email as used for recipient). Upload the modified php file and retry.

Hope this helps some! https://www.arclab.com/en/kb/php/how-to-test-and-fix-php-mail-function.html

613

Answer

Solution:

I had this problem and found that stripping back the headers helped me to get mail out. So this:

$headers  = "MIME-Version: 1.0;\r\n";
$headers .= "Content-type: text/plain; charset=utf-8;\r\n";
$headers .= "To: ".$recipient."\r\n";
$headers .= "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

became this:

$headers = "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

No need for the To: header.

Mail clients are pretty good at sniffing out URLs and rewriting them as a hyperlink. So I didn't bother writing HTML and specifying text/html in the content-type header. I just threw new lines with \r\n in the message body. I appreciate this isn't the coding purist's approach but it works for what I need it for.

327

Answer

Solution:

There are several possibilities:

  1. You're facing a server problem. The server does not have any mail server. So your mail is not working, because your code is fine and mail is working with type.

  2. You are not getting the posted value. Try your code with a static value.

  3. Use SMTP mails to send mail...

773

Answer

Solution:

Although there are portions of this answer that apply to only to the usage of themail() function itself, many of these troubleshooting steps can be applied to any PHP mailing system.

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.

error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");

See How can I get useful error messages in PHP?this answer for more details on this.

Make sure themail() function is called

It may seem silly but a common error is to forget to actually place themail() function in your code. Make sure it is there and not commented out.

Make sure themail() function is called correctly

bool mail ( string $to, string $subject, string $message [, string $additional_headers [, string $additional_parameters ]] )

The mail function takes three required parameters and optionally a fourth and fifth one. If your call tomail() does not have at least three parameters it will fail.

If your call tomail() does not have the correct parameters in the correct order it will also fail.

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 underlogs. Inside will be error messages the server reported, if any, related to your attempts to send emails.

Check for Port connection failure

Port block is a very common problem which most developers face while integrating their code to deliver emails using SMTP. And, this can be easily traced at the server maillogs (the location of server of mail log can vary from server to server, as explained above). In case you are on a shared hosting server, the ports 25 and 587 remain blocked by default. This block is been purposely done by your hosting provider. This is true even for some of the dedicated servers. When these ports are blocked, try to connect using port 2525. If you find that port is also blocked, then the only solution is to contact your hosting provider to unblock these ports.

Most of the hosting providers block these email ports to protect their network from sending any spam emails.

Use ports 25 or 587 for plain/TLS connections and port 465 for SSL connections. For most users, it is suggested to use port 587 to avoid rate limits set by some hosting providers.

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 right afterwards for concrete failures.

Check themail() return value

The function:

ReturnsTRUE 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 aFALSE 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 you receive aTRUE 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.

SoFALSE will help point you in the right direction whereasTRUE does not necessarily mean your email was sent successfully. This is important to note!

Make sure your hosting provider allows you to send emails and does not limit mail sending

Many shared webhosts, especially free webhosting providers, either do not allow emails to be sent from their servers or limit the amount that can be sent during any given time period. This is due to their efforts to limit spammers from taking advantage of their cheaper services.

If you think your host has emailing limits or blocks the sending of emails, check their FAQs to see if they list any such limitations. Otherwise, you may need to reach out to their support to verify if there are any restrictions in place around the sending of emails.

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" <[email protected]> ).
  • Monitor your abuse accounts, such as[email protected] and[email protected]. 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: [email protected]",
    "Reply-To: [email protected]",
    "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 [email protected]", // missing colon
    "Reply To: [email protected]",      // missing hyphen
    "X-Mailer: "PHP"/" . PHP_VERSION      // bad quotes
);

Don't use a fauxFrom: sender

While the mail must have a From: sender, you may not just use any value. In particular user-supplied sender addresses are a surefire way to get mails blocked:

$headers = array("From: $_POST[contactform_sender_email]"); // No!

Reason: your web or sending mail server is not SPF/DKIM-whitelisted to pretend being responsible for @hotmail or @gmail addresses. It may even silently drop mails withFrom: sender domains it's not configured for.

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 = '[email protected]';
// other variables ....
mail($recipient, $subject, $message, $headers); // $recipient should be $to

Another way to test this is to hard code the recipient value into themail() function call:

mail('[email protected]', $subject, $message, $headers);

This can apply to all of themail() 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 toPOST, make sure you are using$_POST to look for your form values. If you have set it toGET or didn't set it at all, make sure you use$_GET to look for your form values.

Make sure your formaction value points to the correct location

Make sure your formaction attribute contains a value that points to your PHP mailing code.

<form action="send_email.php" method="POST">

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 thelocalhost 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 custommail.log

In addition to your MTA's and PHP's log file, you can enable logging for the 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 http://php.net/manual/en/mail.configuration.php for details. (It's best to enable these options in thephp.ini or.user.ini or.htaccess perhaps.)

Check with a mail testing service

There are various delivery and spamminess checking services you can utilize to test your MTA/webserver setup. Typically you send a mail probe To: their address, then get a delivery report and more concrete failures or analyzations later:

Use a different mailer

PHP's built-inmail() 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:

All of which can be combined with a professional SMTP server/service provider. (Because typical 08/15 shared webhosting plans are hit or miss when it comes to email setup/configurability.)

523

Answer

Solution:

Add a mail header in the mail function:

$header = "From: [email protected]\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);

if($status)
{
    echo '<p>Your mail has been sent!</p>';
} else {
    echo '<p>Something went wrong. Please try again!</p>';
}
378

Answer

Solution:

  1. Always try sending headers in the mail function.
  2. If you are sending mail through localhost then do the SMTP settings for sending mail.
  3. If you are sending mail through a server then check the email sending feature is enabled on your server.
671

Answer

Solution:

If you are using an SMTP configuration for sending your email, try using PHPMailer instead. You can download the library from https://github.com/PHPMailer/PHPMailer.

I created my email sending this way:

function send_mail($email, $recipient_name, $message='')
{
    require("phpmailer/class.phpmailer.php");

    $mail = new PHPMailer();

    $mail->CharSet = "utf-8";
    $mail->IsSMTP();                                      // Set mailer to use SMTP
    $mail->Host = "mail.example.com";  // Specify main and backup server
    $mail->SMTPAuth = true;     // Turn on SMTP authentication
    $mail->Username = "myusername";  // SMTP username
    $mail->Password = "[email protected]"; // SMTP password

    $mail->From = "[email protected]";
    $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');
    $mail->addAttachment('files/file.xlsx');

    if(!$mail->Send())
    {
       echo "Message could not be sent. <p>";
       echo "Mailer Error: " . $mail->ErrorInfo;
       exit;
    }

    echo "Message has been sent";
}
794

Answer

Solution:

Just add some headers before sending mail:

<?php 
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com'; 
$to = '[email protected]'; 
$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: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

And one more thing. Themail() function is not working in localhost. Upload your code to a server and try.

95

Answer

Solution:

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('[email protected]', $subject, $message, $headers)

Use'' and not"".

This code works, but the email was received with half an hour lag.

780

Answer

Solution:

Mostly themail() function is disabled in shared hosting. A better option is to use SMTP. The best option would be Gmail or SendGrid.


SMTPconfig.php

<?php 
    $SmtpServer="smtp.*.*";
    $SmtpPort="2525"; //default
    $SmtpUser="***";
    $SmtpPass="***";
?>

SMTPmail.php

<?php
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;
        }
        else
        {
            $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");
            $talk["res"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpUser."\r\n");
            $talk["user"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpPass."\r\n");
            $talk["pass"]=fgets($SMTPIN,256);
            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");
            $talk["send"]=fgets($SMTPIN,256);
            //CLOSE CONNECTION AND EXIT ... 
            fputs ($SMTPIN, "QUIT\r\n"); 
            fclose($SMTPIN); 
            // 
        } 
        return $talk;
    } 
}
?>

contact_email.php

<?php 
include('SMTPconfig.php');
include('SMTPmail.php');
if($_SERVER["REQUEST_METHOD"] == "POST")
{
    $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();
}
?>
689

Answer

Solution:

If you only use themail()function, you need to complete the configuration file.

You need to open the mail expansion, and set theSMTP smtp_port and so on, and most important, your username and your password. Without that, mail cannot be sent. Also, you can use thePHPMail class to send.

31

Answer

Solution:

Try these two things separately and together:

  1. remove theif($_POST['submit']){}
  2. remove$from (just my gut)
356

Answer

Solution:

I think this should do the trick. I just added anif(isset and added concatenation to the variables in the body to separate PHP from HTML.

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: yoursite.com'; 
    $to = '[email protected]'; 
    $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>';
    } 
    else 
    { 
        echo '<p>Something went wrong, go back and try again!</p>'; 
    }
}

?>
25

Answer

Solution:

For anyone who finds this going forward, I would not recommend usingmail. There's some answers that touch on this, but not the why of it.

PHP'smail 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 frommail. 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 usemail to ultimately send the mail, but I would strongly recommend you not do that).

This means 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 callingisSMTP()), you can get a detailed transcript of the SMTP conversation using theSMTPDebug 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. Withmail 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).

772

Answer

Solution:

$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 class="page_speed_1833695416">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>";
}
469

Answer

Solution:

You can use config email by CodeIgniter. For example, using SMTP (simple way):

$config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'mail.domain.com', // Your SMTP host
        'smtp_port' => 26, // Default port for SMTP
        'smtp_user' => '[email protected]',
        'smtp_pass' => 'password',
        'mailtype' => 'html',
        'charset' => 'iso-8859-1',
        'wordwrap' => TRUE
);
$message = 'Your msg';
$this->load->library('email', $config);
$this->email->from('[email protected]', 'Title');
$this->email->to('[email protected]');
$this->email->subject('Header');
$this->email->message($message);

if($this->email->send()) 
{
   // Conditional true
}

It works for me!

281

Answer

Solution:

Try this

if ($_POST['submit']) {
    $success= mail($to, $subject, $body, $from);
    if($success)
    { 
        echo '
        <p>Your message has been sent!</p>
        ';
    } else { 
        echo '
        <p>Something went wrong, go back and try again!</p>
        '; 
    }
}
649

Answer

Solution:

Maybe the problem is the configuration of the mail server. To avoid this type of problems or you do not have to worry about the mail server problem, I recommend you use PHPMailer.

It is a plugin that has everything necessary to send mail, and the only thing you have to take into account is to have the SMTP port (Port: 25 and 465), enabled.

require_once 'PHPMailer/PHPMailer.php';
require_once '/servicios/PHPMailer/SMTP.php';
require_once '/servicios/PHPMailer/Exception.php';

$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
    //Server settings
    $mail->SMTPDebug = 0;
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = '[email protected]';
    $mail->Password = 'contrasenia';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;

    // Recipients
    $mail->setFrom('[email protected]', 'my name');
    $mail->addAddress('[email protected]');

    // Attachments
    $mail->addAttachment('optional file');         // Add files, is optional

    // Content
    $mail->isHTML(true);// Set email format to HTML
    $mail->Subject = utf8_decode("subject");
    $mail->Body    = utf8_decode("mail content");
    $mail->AltBody = '';
    $mail->send();
}
catch (Exception $e) {
    $error = $mail->ErrorInfo;
}
510

Answer

Solution:

First of all, you might have too many parameters for the mail() function... You are able to have of maximum of five,mail(to, subject, message, headers, parameters);

As far as the$from variable goes, that should automatically come from your webhost if your using the Linux cPanel. It automatically comes from your cPanel username and IP address.

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com';
$to = '[email protected]';
$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.

Themail($to, $subject, $message, etc.) in that order, or else there is a chance of it not working.

744

Answer

Solution:

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 www.AceITLab.com, 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.

370

Answer

Solution:

Make sure you have Sendmail installed in your server.

If you have checked your code and verified that there is nothing wrong there, go to /var/mail and check whether that folder is empty.

If it is empty, you will need to do a:

sudo apt-get install sendmail

if you are on an Ubuntu server.

42

Answer

Solution:

For those who do not want to use external mailers and want to mail() on a dedicated Linux server.

The way, how PHP mails, is described inphp.ini in section[mail function].

Parametersendmail-path describes how sendmail is called. The default value issendmail -t -i, so if you get a workingsendmail -t -i < message.txt in the Linux console - you will be done. You could also addmail.log to debug and be sure mail() is really called.

Different MTAs can implementsendmail. They just make a symbolic link to their binaries on that name. For example, in Debian the default is Postfix. Configure your MTA to send mail and test it from the console withsendmail -v -t -i < message.txt. Filemessage.txt should contain all headers of a message and a body, destination address for the envelope will be taken from theTo: header. Example:

From: [email protected]
To: [email protected]
Subject: Test mail via sendmail.

Text body.

I prefer to use ssmtp as MTA because it is simple and does not require running a daemon with opened ports. ssmtp fits only for sending mail from localhost. It also can send authenticated email via your account on a public mail service. Install ssmtp and edit configuration file/etc/ssmtp/ssmtp.conf. To be able also to receive local system mail to Unix accounts (alerts to root from cron jobs, for example) configure/etc/ssmtp/revaliases file.

Here is my configuration for my account on Yandex mail:

[email protected]
mailhub=smtp.yandex.ru:465
FromLineOverride=YES
UseTLS=YES
[email protected]
AuthPass=password
137

Answer

Solution:

Sendmail installation for Debian 10.0.0 ('Buster') was in fact trivial!

php.ini

[mail function]
sendmail_path=/usr/sbin/sendmail -t -i
; (Other directives are mostly windows)

Standard sendmail package install (allowing 'send'):

su -                                        # Install as user 'root'
dpkg --list                                 # Is install necessary?
apt-get install sendmail sendmail-cf m4     # Note multiple package selection
sendmailconfig                              # Respond all 'Y' for new install

Miscellaneous useful commands:

which sendmail                              # /usr/sbin/sendmail
which sendmailconfig                        # /usr/sbin/sendmailconfig
man sendmail                                # Documentation
systemctl restart sendmail                  # As and when required

Verification (of ability to send)

echo "Subject: sendmail test" | sendmail -v <yourEmail>@gmail.com

The above took about 5 minutes. Then I wasted 5 hours... Don't forget to check your spam folder!

620

Answer

Solution:

If you are running this code on a local server (i.e your computer for development purposes) it won't send the email to the recipient. It will create a.txt file in a folder namedmailoutput.

In the case if you are using a free hosing service, like000webhost orhostinger, those service providers disable themail() 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):

<?php
    $to      = '[email protected]';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: [email protected]' . "\r\n" .
        'Reply-To: [email protected]' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
?>
961

Answer

Solution:

You can use thePHPMailer and it works perfectly,here's a code example:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/phpmailer/phpmailer/src/Exception.php';
require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/phpmailer/src/SMTP.php';
$editor = $_POST["editor"];
$subject = $_POST["subject"];
$to = $_POST["to"];

try {

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->Mailer = "smtp";
        $mail->SMTPDebug  = 1;
        $mail->SMTPAuth   = TRUE;
        $mail->SMTPSecure = "tls";
        $mail->Port       = 587;
        $mail->Host       = "smtp.gmail.com";//using smtp server
        $mail->Username   = "[email protected]";//the email which will send the email 
        $mail->Password   = "XXXXXXXXXX";//the password

        $mail->IsHTML(true);
        $mail->AddAddress($to, "recipient-name");
        $mail->SetFrom("[email protected]", "from-name");
        $mail->AddReplyTo("[email protected]", "reply-to-name");
        $mail->Subject = $subject;
        $mail->MsgHTML($editor);




        if (!$mail->Send()) {
            echo "Error while sending Email.";
            var_dump($mail);
        } else {
            echo "Email sent successfully";
        }
    }
} catch (Exception $e) {
    echo $e->getMessage();
}
208

Answer

Solution:

You can see your errors by:

error_reporting(E_ALL);

And my sample code is:

<?php
    use PHPMailer\PHPMailer\PHPMailer;
    require 'PHPMailer.php';
    require 'SMTP.php';
    require 'Exception.php';

    $name = $_POST['name'];
    $mailid = $_POST['mail'];
    $mail = new PHPMailer;
    $mail->IsSMTP();
    $mail->SMTPDebug = 0;                   // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';         // Specify main and backup server
    $mail->Port = 587;                      // Set the SMTP port
    $mail->SMTPAuth = true;                 // Enable SMTP authentication
    $mail->Username = '[email protected]';  // SMTP username
    $mail->Password = 'password';           // SMTP password
    $mail->SMTPSecure = 'tls';              // Enable encryption, 'ssl' also accepted

    $mail->From = '[email protected]';
    $mail->FromName = 'name';
    $mail->AddAddress($mailid, $name);       // Name is optional
    $mail->IsHTML(true);                     // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'Here is your message' ;
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
    if (!$mail->Send()) {
       echo 'Message could not be sent.';
       echo 'Mailer Error: ' . $mail->ErrorInfo;
       exit;
    }
    echo 'Message has been sent';
?>
554

Answer

Solution:

If you're stuck with an app hosted on Hostgator, this is what solved my problem. Thanks a lot to the guy who posted the detailed solution. In case the link goes offline one day, there you have the summary:

  • Look for the sendmail path in your server. A simple way to check it, is to temporarily write the following code in a page which only you will access, to read the generated info:<?php phpinfo(); ?>. Open this page, and look forsendmail path. (Then, don't forget to remove this code!)
  • Problem and fix: if your sendmail path is saying only-t -i, then edit your server'sphp.ini and add the following line:sendmail_path = /usr/sbin/sendmail -t -i;

But, after being able to send mail with PHPmail() function, I learned that it sends not authenticated email, what created another issue. The emails were all falling in my Hotmail's junk mail box, and some emails were never delivered, which I guess is related to the fact that they are not authenticated. That's why I decided to switch frommail() toPHPMailer with SMTP, after all.

486

Answer

Solution:

It may be a problem with "From:" $email address in this part of the $headers:

From: \"$name\" <$email>

To try it out, send an email without the headers part, like:

mail('[email protected]', $subject, $message); 

If that is a case, try using an email account that is already created at the system you are trying to send mail from.

746

Answer

Solution:

<?php

$to       = '[email protected]';
$subject  = 'Write your email subject here.';
$message  = '
<html>
<head>
<title>Title here</title>
</head>
<body>
<p>Message here</p>
</body>
</html>
';

// Carriage return type (RFC).
$eol = "\r\n";

$headers  = "Reply-To: Name <[email protected]>".$eol;
$headers .= "Return-Path: Name <[email protected]>".$eol;
$headers .= "From: Name <[email protected]>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/html; charset=iso-8859-1".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;


mail($to, $subject, $message, $headers);

Sending HTML email While sending an email message you can specify a Mime version, content type and character set to send an HTML email.

Example The above example will send an HTML email message to [email protected] You can code this program in such a way that it should receive all content from the user and then it should send an email.

778

Answer

Solution:

What solved this issue for me was that some providers don't allow external recipients when using php mail:

Change the recipient ($recipient) in the code to a local recipient. This means use an email address from the server's domain, for example if your server domain is www.yourdomain.com then the recipient's email should be [email protected] Upload the modified php file and retry. If it's still not working: change the sender ($sender) to a local email (use the same email as used for recipient). Upload the modified php file and retry.

Hope this helps some! https://www.arclab.com/en/kb/php/how-to-test-and-fix-php-mail-function.html

768

Answer

Solution:

I had this problem and found that stripping back the headers helped me to get mail out. So this:

$headers  = "MIME-Version: 1.0;\r\n";
$headers .= "Content-type: text/plain; charset=utf-8;\r\n";
$headers .= "To: ".$recipient."\r\n";
$headers .= "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

became this:

$headers = "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

No need for the To: header.

Mail clients are pretty good at sniffing out URLs and rewriting them as a hyperlink. So I didn't bother writing HTML and specifying text/html in the content-type header. I just threw new lines with \r\n in the message body. I appreciate this isn't the coding purist's approach but it works for what I need it for.

607

Answer

Solution:

There are several possibilities:

  1. You're facing a server problem. The server does not have any mail server. So your mail is not working, because your code is fine and mail is working with type.

  2. You are not getting the posted value. Try your code with a static value.

  3. Use SMTP mails to send mail...

930

Answer

Solution:

Although there are portions of this answer that apply to only to the usage of themail() function itself, many of these troubleshooting steps can be applied to any PHP mailing system.

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.

error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");

See How can I get useful error messages in PHP?this answer for more details on this.

Make sure themail() function is called

It may seem silly but a common error is to forget to actually place themail() function in your code. Make sure it is there and not commented out.

Make sure themail() function is called correctly

bool mail ( string $to, string $subject, string $message [, string $additional_headers [, string $additional_parameters ]] )

The mail function takes three required parameters and optionally a fourth and fifth one. If your call tomail() does not have at least three parameters it will fail.

If your call tomail() does not have the correct parameters in the correct order it will also fail.

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 underlogs. Inside will be error messages the server reported, if any, related to your attempts to send emails.

Check for Port connection failure

Port block is a very common problem which most developers face while integrating their code to deliver emails using SMTP. And, this can be easily traced at the server maillogs (the location of server of mail log can vary from server to server, as explained above). In case you are on a shared hosting server, the ports 25 and 587 remain blocked by default. This block is been purposely done by your hosting provider. This is true even for some of the dedicated servers. When these ports are blocked, try to connect using port 2525. If you find that port is also blocked, then the only solution is to contact your hosting provider to unblock these ports.

Most of the hosting providers block these email ports to protect their network from sending any spam emails.

Use ports 25 or 587 for plain/TLS connections and port 465 for SSL connections. For most users, it is suggested to use port 587 to avoid rate limits set by some hosting providers.

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 right afterwards for concrete failures.

Check themail() return value

The function:

ReturnsTRUE 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 aFALSE 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 you receive aTRUE 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.

SoFALSE will help point you in the right direction whereasTRUE does not necessarily mean your email was sent successfully. This is important to note!

Make sure your hosting provider allows you to send emails and does not limit mail sending

Many shared webhosts, especially free webhosting providers, either do not allow emails to be sent from their servers or limit the amount that can be sent during any given time period. This is due to their efforts to limit spammers from taking advantage of their cheaper services.

If you think your host has emailing limits or blocks the sending of emails, check their FAQs to see if they list any such limitations. Otherwise, you may need to reach out to their support to verify if there are any restrictions in place around the sending of emails.

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" <[email protected]> ).
  • Monitor your abuse accounts, such as[email protected] and[email protected]. 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: [email protected]xample.com",
    "Reply-To: [email protected]",
    "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 [email protected]", // missing colon
    "Reply To: [email protected]",      // missing hyphen
    "X-Mailer: "PHP"/" . PHP_VERSION      // bad quotes
);

Don't use a fauxFrom: sender

While the mail must have a From: sender, you may not just use any value. In particular user-supplied sender addresses are a surefire way to get mails blocked:

$headers = array("From: $_POST[contactform_sender_email]"); // No!

Reason: your web or sending mail server is not SPF/DKIM-whitelisted to pretend being responsible for @hotmail or @gmail addresses. It may even silently drop mails withFrom: sender domains it's not configured for.

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 = '[email protected]';
// other variables ....
mail($recipient, $subject, $message, $headers); // $recipient should be $to

Another way to test this is to hard code the recipient value into themail() function call:

mail('[email protected]', $subject, $message, $headers);

This can apply to all of themail() 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 toPOST, make sure you are using$_POST to look for your form values. If you have set it toGET or didn't set it at all, make sure you use$_GET to look for your form values.

Make sure your formaction value points to the correct location

Make sure your formaction attribute contains a value that points to your PHP mailing code.

<form action="send_email.php" method="POST">

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 thelocalhost 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 custommail.log

In addition to your MTA's and PHP's log file, you can enable logging for the 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 http://php.net/manual/en/mail.configuration.php for details. (It's best to enable these options in thephp.ini or.user.ini or.htaccess perhaps.)

Check with a mail testing service

There are various delivery and spamminess checking services you can utilize to test your MTA/webserver setup. Typically you send a mail probe To: their address, then get a delivery report and more concrete failures or analyzations later:

Use a different mailer

PHP's built-inmail() 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:

All of which can be combined with a professional SMTP server/service provider. (Because typical 08/15 shared webhosting plans are hit or miss when it comes to email setup/configurability.)

413

Answer

Solution:

Add a mail header in the mail function:

$header = "From: [email protected]\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);

if($status)
{
    echo '<p>Your mail has been sent!</p>';
} else {
    echo '<p>Something went wrong. Please try again!</p>';
}
35

Answer

Solution:

  1. Always try sending headers in the mail function.
  2. If you are sending mail through localhost then do the SMTP settings for sending mail.
  3. If you are sending mail through a server then check the email sending feature is enabled on your server.
422

Answer

Solution:

If you are using an SMTP configuration for sending your email, try using PHPMailer instead. You can download the library from https://github.com/PHPMailer/PHPMailer.

I created my email sending this way:

function send_mail($email, $recipient_name, $message='')
{
    require("phpmailer/class.phpmailer.php");

    $mail = new PHPMailer();

    $mail->CharSet = "utf-8";
    $mail->IsSMTP();                                      // Set mailer to use SMTP
    $mail->Host = "mail.example.com";  // Specify main and backup server
    $mail->SMTPAuth = true;     // Turn on SMTP authentication
    $mail->Username = "myusername";  // SMTP username
    $mail->Password = "[email protected]"; // SMTP password

    $mail->From = "[email protected]";
    $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');
    $mail->addAttachment('files/file.xlsx');

    if(!$mail->Send())
    {
       echo "Message could not be sent. <p>";
       echo "Mailer Error: " . $mail->ErrorInfo;
       exit;
    }

    echo "Message has been sent";
}
599

Answer

Solution:

Just add some headers before sending mail:

<?php 
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com'; 
$to = '[email protected]'; 
$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: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

And one more thing. Themail() function is not working in localhost. Upload your code to a server and try.

577

Answer

Solution:

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('[email protected]', $subject, $message, $headers)

Use'' and not"".

This code works, but the email was received with half an hour lag.

145

Answer

Solution:

Mostly themail() function is disabled in shared hosting. A better option is to use SMTP. The best option would be Gmail or SendGrid.


SMTPconfig.php

<?php 
    $SmtpServer="smtp.*.*";
    $SmtpPort="2525"; //default
    $SmtpUser="***";
    $SmtpPass="***";
?>

SMTPmail.php

<?php
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;
        }
        else
        {
            $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");
            $talk["res"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpUser."\r\n");
            $talk["user"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpPass."\r\n");
            $talk["pass"]=fgets($SMTPIN,256);
            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");
            $talk["send"]=fgets($SMTPIN,256);
            //CLOSE CONNECTION AND EXIT ... 
            fputs ($SMTPIN, "QUIT\r\n"); 
            fclose($SMTPIN); 
            // 
        } 
        return $talk;
    } 
}
?>

contact_email.php

<?php 
include('SMTPconfig.php');
include('SMTPmail.php');
if($_SERVER["REQUEST_METHOD"] == "POST")
{
    $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();
}
?>
375

Answer

Solution:

If you only use themail()function, you need to complete the configuration file.

You need to open the mail expansion, and set theSMTP smtp_port and so on, and most important, your username and your password. Without that, mail cannot be sent. Also, you can use thePHPMail class to send.

867

Answer

Solution:

Try these two things separately and together:

  1. remove theif($_POST['submit']){}
  2. remove$from (just my gut)
782

Answer

Solution:

I think this should do the trick. I just added anif(isset and added concatenation to the variables in the body to separate PHP from HTML.

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: yoursite.com'; 
    $to = '[email protected]'; 
    $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>';
    } 
    else 
    { 
        echo '<p>Something went wrong, go back and try again!</p>'; 
    }
}

?>
892

Answer

Solution:

For anyone who finds this going forward, I would not recommend usingmail. There's some answers that touch on this, but not the why of it.

PHP'smail 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 frommail. 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 usemail to ultimately send the mail, but I would strongly recommend you not do that).

This means 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 callingisSMTP()), you can get a detailed transcript of the SMTP conversation using theSMTPDebug 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. Withmail 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).

312

Answer

Solution:

$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 class="page_speed_1833695416">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>";
}
919

Answer

Solution:

You can use config email by CodeIgniter. For example, using SMTP (simple way):

$config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'mail.domain.com', // Your SMTP host
        'smtp_port' => 26, // Default port for SMTP
        'smtp_user' => '[email protected]',
        'smtp_pass' => 'password',
        'mailtype' => 'html',
        'charset' => 'iso-8859-1',
        'wordwrap' => TRUE
);
$message = 'Your msg';
$this->load->library('email', $config);
$this->email->from('[email protected]', 'Title');
$this->email->to('[email protected]');
$this->email->subject('Header');
$this->email->message($message);

if($this->email->send()) 
{
   // Conditional true
}

It works for me!

73

Answer

Solution:

Try this

if ($_POST['submit']) {
    $success= mail($to, $subject, $body, $from);
    if($success)
    { 
        echo '
        <p>Your message has been sent!</p>
        ';
    } else { 
        echo '
        <p>Something went wrong, go back and try again!</p>
        '; 
    }
}
389

Answer

Solution:

Maybe the problem is the configuration of the mail server. To avoid this type of problems or you do not have to worry about the mail server problem, I recommend you use PHPMailer.

It is a plugin that has everything necessary to send mail, and the only thing you have to take into account is to have the SMTP port (Port: 25 and 465), enabled.

require_once 'PHPMailer/PHPMailer.php';
require_once '/servicios/PHPMailer/SMTP.php';
require_once '/servicios/PHPMailer/Exception.php';

$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
    //Server settings
    $mail->SMTPDebug = 0;
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = '[email protected]';
    $mail->Password = 'contrasenia';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;

    // Recipients
    $mail->setFrom('[email protected]', 'my name');
    $mail->addAddress('[email protected]');

    // Attachments
    $mail->addAttachment('optional file');         // Add files, is optional

    // Content
    $mail->isHTML(true);// Set email format to HTML
    $mail->Subject = utf8_decode("subject");
    $mail->Body    = utf8_decode("mail content");
    $mail->AltBody = '';
    $mail->send();
}
catch (Exception $e) {
    $error = $mail->ErrorInfo;
}
82

Answer

Solution:

First of all, you might have too many parameters for the mail() function... You are able to have of maximum of five,mail(to, subject, message, headers, parameters);

As far as the$from variable goes, that should automatically come from your webhost if your using the Linux cPanel. It automatically comes from your cPanel username and IP address.

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com';
$to = '[email protected]';
$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.

Themail($to, $subject, $message, etc.) in that order, or else there is a chance of it not working.

952

Answer

Solution:

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 www.AceITLab.com, 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.

80

Answer

Solution:

Make sure you have Sendmail installed in your server.

If you have checked your code and verified that there is nothing wrong there, go to /var/mail and check whether that folder is empty.

If it is empty, you will need to do a:

sudo apt-get install sendmail

if you are on an Ubuntu server.

465

Answer

Solution:

For those who do not want to use external mailers and want to mail() on a dedicated Linux server.

The way, how PHP mails, is described inphp.ini in section[mail function].

Parametersendmail-path describes how sendmail is called. The default value issendmail -t -i, so if you get a workingsendmail -t -i < message.txt in the Linux console - you will be done. You could also addmail.log to debug and be sure mail() is really called.

Different MTAs can implementsendmail. They just make a symbolic link to their binaries on that name. For example, in Debian the default is Postfix. Configure your MTA to send mail and test it from the console withsendmail -v -t -i < message.txt. Filemessage.txt should contain all headers of a message and a body, destination address for the envelope will be taken from theTo: header. Example:

From: [email protected]
To: [email protected]
Subject: Test mail via sendmail.

Text body.

I prefer to use ssmtp as MTA because it is simple and does not require running a daemon with opened ports. ssmtp fits only for sending mail from localhost. It also can send authenticated email via your account on a public mail service. Install ssmtp and edit configuration file/etc/ssmtp/ssmtp.conf. To be able also to receive local system mail to Unix accounts (alerts to root from cron jobs, for example) configure/etc/ssmtp/revaliases file.

Here is my configuration for my account on Yandex mail:

[email protected]
mailhub=smtp.yandex.ru:465
FromLineOverride=YES
UseTLS=YES
[email protected]
AuthPass=password
205

Answer

Solution:

Sendmail installation for Debian 10.0.0 ('Buster') was in fact trivial!

php.ini

[mail function]
sendmail_path=/usr/sbin/sendmail -t -i
; (Other directives are mostly windows)

Standard sendmail package install (allowing 'send'):

su -                                        # Install as user 'root'
dpkg --list                                 # Is install necessary?
apt-get install sendmail sendmail-cf m4     # Note multiple package selection
sendmailconfig                              # Respond all 'Y' for new install

Miscellaneous useful commands:

which sendmail                              # /usr/sbin/sendmail
which sendmailconfig                        # /usr/sbin/sendmailconfig
man sendmail                                # Documentation
systemctl restart sendmail                  # As and when required

Verification (of ability to send)

echo "Subject: sendmail test" | sendmail -v <yourEmail>@gmail.com

The above took about 5 minutes. Then I wasted 5 hours... Don't forget to check your spam folder!

963

Answer

Solution:

If you are running this code on a local server (i.e your computer for development purposes) it won't send the email to the recipient. It will create a.txt file in a folder namedmailoutput.

In the case if you are using a free hosing service, like000webhost orhostinger, those service providers disable themail() 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):

<?php
    $to      = '[email protected]';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: [email protected]' . "\r\n" .
        'Reply-To: [email protected]' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
?>
182

Answer

Solution:

You can use thePHPMailer and it works perfectly,here's a code example:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/phpmailer/phpmailer/src/Exception.php';
require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/phpmailer/src/SMTP.php';
$editor = $_POST["editor"];
$subject = $_POST["subject"];
$to = $_POST["to"];

try {

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->Mailer = "smtp";
        $mail->SMTPDebug  = 1;
        $mail->SMTPAuth   = TRUE;
        $mail->SMTPSecure = "tls";
        $mail->Port       = 587;
        $mail->Host       = "smtp.gmail.com";//using smtp server
        $mail->Username   = "[email protected]";//the email which will send the email 
        $mail->Password   = "XXXXXXXXXX";//the password

        $mail->IsHTML(true);
        $mail->AddAddress($to, "recipient-name");
        $mail->SetFrom("[email protected]", "from-name");
        $mail->AddReplyTo("[email protected]", "reply-to-name");
        $mail->Subject = $subject;
        $mail->MsgHTML($editor);




        if (!$mail->Send()) {
            echo "Error while sending Email.";
            var_dump($mail);
        } else {
            echo "Email sent successfully";
        }
    }
} catch (Exception $e) {
    echo $e->getMessage();
}
279

Answer

Solution:

You can see your errors by:

error_reporting(E_ALL);

And my sample code is:

<?php
    use PHPMailer\PHPMailer\PHPMailer;
    require 'PHPMailer.php';
    require 'SMTP.php';
    require 'Exception.php';

    $name = $_POST['name'];
    $mailid = $_POST['mail'];
    $mail = new PHPMailer;
    $mail->IsSMTP();
    $mail->SMTPDebug = 0;                   // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';         // Specify main and backup server
    $mail->Port = 587;                      // Set the SMTP port
    $mail->SMTPAuth = true;                 // Enable SMTP authentication
    $mail->Username = '[email protected]';  // SMTP username
    $mail->Password = 'password';           // SMTP password
    $mail->SMTPSecure = 'tls';              // Enable encryption, 'ssl' also accepted

    $mail->From = '[email protected]';
    $mail->FromName = 'name';
    $mail->AddAddress($mailid, $name);       // Name is optional
    $mail->IsHTML(true);                     // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'Here is your message' ;
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
    if (!$mail->Send()) {
       echo 'Message could not be sent.';
       echo 'Mailer Error: ' . $mail->ErrorInfo;
       exit;
    }
    echo 'Message has been sent';
?>
524

Answer

Solution:

If you're stuck with an app hosted on Hostgator, this is what solved my problem. Thanks a lot to the guy who posted the detailed solution. In case the link goes offline one day, there you have the summary:

  • Look for the sendmail path in your server. A simple way to check it, is to temporarily write the following code in a page which only you will access, to read the generated info:<?php phpinfo(); ?>. Open this page, and look forsendmail path. (Then, don't forget to remove this code!)
  • Problem and fix: if your sendmail path is saying only-t -i, then edit your server'sphp.ini and add the following line:sendmail_path = /usr/sbin/sendmail -t -i;

But, after being able to send mail with PHPmail() function, I learned that it sends not authenticated email, what created another issue. The emails were all falling in my Hotmail's junk mail box, and some emails were never delivered, which I guess is related to the fact that they are not authenticated. That's why I decided to switch frommail() toPHPMailer with SMTP, after all.

522

Answer

Solution:

It may be a problem with "From:" $email address in this part of the $headers:

From: \"$name\" <$email>

To try it out, send an email without the headers part, like:

mail('[email protected]', $subject, $message); 

If that is a case, try using an email account that is already created at the system you are trying to send mail from.

382

Answer

Solution:

<?php

$to       = '[email protected]';
$subject  = 'Write your email subject here.';
$message  = '
<html>
<head>
<title>Title here</title>
</head>
<body>
<p>Message here</p>
</body>
</html>
';

// Carriage return type (RFC).
$eol = "\r\n";

$headers  = "Reply-To: Name <[email protected]>".$eol;
$headers .= "Return-Path: Name <[email protected]>".$eol;
$headers .= "From: Name <[email protected]>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/html; charset=iso-8859-1".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;


mail($to, $subject, $message, $headers);

Sending HTML email While sending an email message you can specify a Mime version, content type and character set to send an HTML email.

Example The above example will send an HTML email message to [email protected] You can code this program in such a way that it should receive all content from the user and then it should send an email.

111

Answer

Solution:

What solved this issue for me was that some providers don't allow external recipients when using php mail:

Change the recipient ($recipient) in the code to a local recipient. This means use an email address from the server's domain, for example if your server domain is www.yourdomain.com then the recipient's email should be [email protected] Upload the modified php file and retry. If it's still not working: change the sender ($sender) to a local email (use the same email as used for recipient). Upload the modified php file and retry.

Hope this helps some! https://www.arclab.com/en/kb/php/how-to-test-and-fix-php-mail-function.html

823

Answer

Solution:

I had this problem and found that stripping back the headers helped me to get mail out. So this:

$headers  = "MIME-Version: 1.0;\r\n";
$headers .= "Content-type: text/plain; charset=utf-8;\r\n";
$headers .= "To: ".$recipient."\r\n";
$headers .= "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

became this:

$headers = "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

No need for the To: header.

Mail clients are pretty good at sniffing out URLs and rewriting them as a hyperlink. So I didn't bother writing HTML and specifying text/html in the content-type header. I just threw new lines with \r\n in the message body. I appreciate this isn't the coding purist's approach but it works for what I need it for.

446

Answer

Solution:

There are several possibilities:

  1. You're facing a server problem. The server does not have any mail server. So your mail is not working, because your code is fine and mail is working with type.

  2. You are not getting the posted value. Try your code with a static value.

  3. Use SMTP mails to send mail...

371

Answer

Solution:

Although there are portions of this answer that apply to only to the usage of themail() function itself, many of these troubleshooting steps can be applied to any PHP mailing system.

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.

error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");

See How can I get useful error messages in PHP?this answer for more details on this.

Make sure themail() function is called

It may seem silly but a common error is to forget to actually place themail() function in your code. Make sure it is there and not commented out.

Make sure themail() function is called correctly

bool mail ( string $to, string $subject, string $message [, string $additional_headers [, string $additional_parameters ]] )

The mail function takes three required parameters and optionally a fourth and fifth one. If your call tomail() does not have at least three parameters it will fail.

If your call tomail() does not have the correct parameters in the correct order it will also fail.

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 underlogs. Inside will be error messages the server reported, if any, related to your attempts to send emails.

Check for Port connection failure

Port block is a very common problem which most developers face while integrating their code to deliver emails using SMTP. And, this can be easily traced at the server maillogs (the location of server of mail log can vary from server to server, as explained above). In case you are on a shared hosting server, the ports 25 and 587 remain blocked by default. This block is been purposely done by your hosting provider. This is true even for some of the dedicated servers. When these ports are blocked, try to connect using port 2525. If you find that port is also blocked, then the only solution is to contact your hosting provider to unblock these ports.

Most of the hosting providers block these email ports to protect their network from sending any spam emails.

Use ports 25 or 587 for plain/TLS connections and port 465 for SSL connections. For most users, it is suggested to use port 587 to avoid rate limits set by some hosting providers.

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 right afterwards for concrete failures.

Check themail() return value

The function:

ReturnsTRUE 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 aFALSE 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 you receive aTRUE 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.

SoFALSE will help point you in the right direction whereasTRUE does not necessarily mean your email was sent successfully. This is important to note!

Make sure your hosting provider allows you to send emails and does not limit mail sending

Many shared webhosts, especially free webhosting providers, either do not allow emails to be sent from their servers or limit the amount that can be sent during any given time period. This is due to their efforts to limit spammers from taking advantage of their cheaper services.

If you think your host has emailing limits or blocks the sending of emails, check their FAQs to see if they list any such limitations. Otherwise, you may need to reach out to their support to verify if there are any restrictions in place around the sending of emails.

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" <[email protected]> ).
  • Monitor your abuse accounts, such as[email protected] and[email protected]. 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: [email protected]",
    "Reply-To: [email protected]",
    "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 [email protected]", // missing colon
    "Reply To: [email protected]",      // missing hyphen
    "X-Mailer: "PHP"/" . PHP_VERSION      // bad quotes
);

Don't use a fauxFrom: sender

While the mail must have a From: sender, you may not just use any value. In particular user-supplied sender addresses are a surefire way to get mails blocked:

$headers = array("From: $_POST[contactform_sender_email]"); // No!

Reason: your web or sending mail server is not SPF/DKIM-whitelisted to pretend being responsible for @hotmail or @gmail addresses. It may even silently drop mails withFrom: sender domains it's not configured for.

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 = '[email protected]';
// other variables ....
mail($recipient, $subject, $message, $headers); // $recipient should be $to

Another way to test this is to hard code the recipient value into themail() function call:

mail('[email protected]', $subject, $message, $headers);

This can apply to all of themail() 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 toPOST, make sure you are using$_POST to look for your form values. If you have set it toGET or didn't set it at all, make sure you use$_GET to look for your form values.

Make sure your formaction value points to the correct location

Make sure your formaction attribute contains a value that points to your PHP mailing code.

<form action="send_email.php" method="POST">

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 thelocalhost 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 custommail.log

In addition to your MTA's and PHP's log file, you can enable logging for the 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 http://php.net/manual/en/mail.configuration.php for details. (It's best to enable these options in thephp.ini or.user.ini or.htaccess perhaps.)

Check with a mail testing service

There are various delivery and spamminess checking services you can utilize to test your MTA/webserver setup. Typically you send a mail probe To: their address, then get a delivery report and more concrete failures or analyzations later:

Use a different mailer

PHP's built-inmail() 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:

All of which can be combined with a professional SMTP server/service provider. (Because typical 08/15 shared webhosting plans are hit or miss when it comes to email setup/configurability.)

611

Answer

Solution:

Add a mail header in the mail function:

$header = "From: [email protected]\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);

if($status)
{
    echo '<p>Your mail has been sent!</p>';
} else {
    echo '<p>Something went wrong. Please try again!</p>';
}
193

Answer

Solution:

  1. Always try sending headers in the mail function.
  2. If you are sending mail through localhost then do the SMTP settings for sending mail.
  3. If you are sending mail through a server then check the email sending feature is enabled on your server.
667

Answer

Solution:

If you are using an SMTP configuration for sending your email, try using PHPMailer instead. You can download the library from https://github.com/PHPMailer/PHPMailer.

I created my email sending this way:

function send_mail($email, $recipient_name, $message='')
{
    require("phpmailer/class.phpmailer.php");

    $mail = new PHPMailer();

    $mail->CharSet = "utf-8";
    $mail->IsSMTP();                                      // Set mailer to use SMTP
    $mail->Host = "mail.example.com";  // Specify main and backup server
    $mail->SMTPAuth = true;     // Turn on SMTP authentication
    $mail->Username = "myusername";  // SMTP username
    $mail->Password = "[email protected]"; // SMTP password

    $mail->From = "[email protected]";
    $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');
    $mail->addAttachment('files/file.xlsx');

    if(!$mail->Send())
    {
       echo "Message could not be sent. <p>";
       echo "Mailer Error: " . $mail->ErrorInfo;
       exit;
    }

    echo "Message has been sent";
}
222

Answer

Solution:

Just add some headers before sending mail:

<?php 
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com'; 
$to = '[email protected]'; 
$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: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

And one more thing. Themail() function is not working in localhost. Upload your code to a server and try.

177

Answer

Solution:

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('[email protected]', $subject, $message, $headers)

Use'' and not"".

This code works, but the email was received with half an hour lag.

548

Answer

Solution:

Mostly themail() function is disabled in shared hosting. A better option is to use SMTP. The best option would be Gmail or SendGrid.


SMTPconfig.php

<?php 
    $SmtpServer="smtp.*.*";
    $SmtpPort="2525"; //default
    $SmtpUser="***";
    $SmtpPass="***";
?>

SMTPmail.php

<?php
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;
        }
        else
        {
            $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");
            $talk["res"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpUser."\r\n");
            $talk["user"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpPass."\r\n");
            $talk["pass"]=fgets($SMTPIN,256);
            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");
            $talk["send"]=fgets($SMTPIN,256);
            //CLOSE CONNECTION AND EXIT ... 
            fputs ($SMTPIN, "QUIT\r\n"); 
            fclose($SMTPIN); 
            // 
        } 
        return $talk;
    } 
}
?>

contact_email.php

<?php 
include('SMTPconfig.php');
include('SMTPmail.php');
if($_SERVER["REQUEST_METHOD"] == "POST")
{
    $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();
}
?>
82

Answer

Solution:

If you only use themail()function, you need to complete the configuration file.

You need to open the mail expansion, and set theSMTP smtp_port and so on, and most important, your username and your password. Without that, mail cannot be sent. Also, you can use thePHPMail class to send.

932

Answer

Solution:

Try these two things separately and together:

  1. remove theif($_POST['submit']){}
  2. remove$from (just my gut)
246

Answer

Solution:

I think this should do the trick. I just added anif(isset and added concatenation to the variables in the body to separate PHP from HTML.

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: yoursite.com'; 
    $to = '[email protected]'; 
    $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>';
    } 
    else 
    { 
        echo '<p>Something went wrong, go back and try again!</p>'; 
    }
}

?>
640

Answer

Solution:

For anyone who finds this going forward, I would not recommend usingmail. There's some answers that touch on this, but not the why of it.

PHP'smail 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 frommail. 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 usemail to ultimately send the mail, but I would strongly recommend you not do that).

This means 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 callingisSMTP()), you can get a detailed transcript of the SMTP conversation using theSMTPDebug 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. Withmail 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).

459

Answer

Solution:

$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 class="page_speed_1833695416">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>";
}
235

Answer

Solution:

You can use config email by CodeIgniter. For example, using SMTP (simple way):

$config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'mail.domain.com', // Your SMTP host
        'smtp_port' => 26, // Default port for SMTP
        'smtp_user' => '[email protected]',
        'smtp_pass' => 'password',
        'mailtype' => 'html',
        'charset' => 'iso-8859-1',
        'wordwrap' => TRUE
);
$message = 'Your msg';
$this->load->library('email', $config);
$this->email->from('[email protected]', 'Title');
$this->email->to('[email protected]');
$this->email->subject('Header');
$this->email->message($message);

if($this->email->send()) 
{
   // Conditional true
}

It works for me!

305

Answer

Solution:

Try this

if ($_POST['submit']) {
    $success= mail($to, $subject, $body, $from);
    if($success)
    { 
        echo '
        <p>Your message has been sent!</p>
        ';
    } else { 
        echo '
        <p>Something went wrong, go back and try again!</p>
        '; 
    }
}
260

Answer

Solution:

Maybe the problem is the configuration of the mail server. To avoid this type of problems or you do not have to worry about the mail server problem, I recommend you use PHPMailer.

It is a plugin that has everything necessary to send mail, and the only thing you have to take into account is to have the SMTP port (Port: 25 and 465), enabled.

require_once 'PHPMailer/PHPMailer.php';
require_once '/servicios/PHPMailer/SMTP.php';
require_once '/servicios/PHPMailer/Exception.php';

$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
    //Server settings
    $mail->SMTPDebug = 0;
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = '[email protected]';
    $mail->Password = 'contrasenia';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;

    // Recipients
    $mail->setFrom('[email protected]', 'my name');
    $mail->addAddress('[email protected]');

    // Attachments
    $mail->addAttachment('optional file');         // Add files, is optional

    // Content
    $mail->isHTML(true);// Set email format to HTML
    $mail->Subject = utf8_decode("subject");
    $mail->Body    = utf8_decode("mail content");
    $mail->AltBody = '';
    $mail->send();
}
catch (Exception $e) {
    $error = $mail->ErrorInfo;
}
336

Answer

Solution:

First of all, you might have too many parameters for the mail() function... You are able to have of maximum of five,mail(to, subject, message, headers, parameters);

As far as the$from variable goes, that should automatically come from your webhost if your using the Linux cPanel. It automatically comes from your cPanel username and IP address.

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com';
$to = '[email protected]';
$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.

Themail($to, $subject, $message, etc.) in that order, or else there is a chance of it not working.

297

Answer

Solution:

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 www.AceITLab.com, 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.

709

Answer

Solution:

Make sure you have Sendmail installed in your server.

If you have checked your code and verified that there is nothing wrong there, go to /var/mail and check whether that folder is empty.

If it is empty, you will need to do a:

sudo apt-get install sendmail

if you are on an Ubuntu server.

105

Answer

Solution:

For those who do not want to use external mailers and want to mail() on a dedicated Linux server.

The way, how PHP mails, is described inphp.ini in section[mail function].

Parametersendmail-path describes how sendmail is called. The default value issendmail -t -i, so if you get a workingsendmail -t -i < message.txt in the Linux console - you will be done. You could also addmail.log to debug and be sure mail() is really called.

Different MTAs can implementsendmail. They just make a symbolic link to their binaries on that name. For example, in Debian the default is Postfix. Configure your MTA to send mail and test it from the console withsendmail -v -t -i < message.txt. Filemessage.txt should contain all headers of a message and a body, destination address for the envelope will be taken from theTo: header. Example:

From: [email protected]
To: [email protected]
Subject: Test mail via sendmail.

Text body.

I prefer to use ssmtp as MTA because it is simple and does not require running a daemon with opened ports. ssmtp fits only for sending mail from localhost. It also can send authenticated email via your account on a public mail service. Install ssmtp and edit configuration file/etc/ssmtp/ssmtp.conf. To be able also to receive local system mail to Unix accounts (alerts to root from cron jobs, for example) configure/etc/ssmtp/revaliases file.

Here is my configuration for my account on Yandex mail:

[email protected]
mailhub=smtp.yandex.ru:465
FromLineOverride=YES
UseTLS=YES
[email protected]
AuthPass=password
943

Answer

Solution:

Sendmail installation for Debian 10.0.0 ('Buster') was in fact trivial!

php.ini

[mail function]
sendmail_path=/usr/sbin/sendmail -t -i
; (Other directives are mostly windows)

Standard sendmail package install (allowing 'send'):

su -                                        # Install as user 'root'
dpkg --list                                 # Is install necessary?
apt-get install sendmail sendmail-cf m4     # Note multiple package selection
sendmailconfig                              # Respond all 'Y' for new install

Miscellaneous useful commands:

which sendmail                              # /usr/sbin/sendmail
which sendmailconfig                        # /usr/sbin/sendmailconfig
man sendmail                                # Documentation
systemctl restart sendmail                  # As and when required

Verification (of ability to send)

echo "Subject: sendmail test" | sendmail -v <yourEmail>@gmail.com

The above took about 5 minutes. Then I wasted 5 hours... Don't forget to check your spam folder!

104

Answer

Solution:

If you are running this code on a local server (i.e your computer for development purposes) it won't send the email to the recipient. It will create a.txt file in a folder namedmailoutput.

In the case if you are using a free hosing service, like000webhost orhostinger, those service providers disable themail() 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):

<?php
    $to      = '[email protected]';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: [email protected]' . "\r\n" .
        'Reply-To: [email protected]' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
?>
948

Answer

Solution:

You can use thePHPMailer and it works perfectly,here's a code example:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/phpmailer/phpmailer/src/Exception.php';
require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/phpmailer/src/SMTP.php';
$editor = $_POST["editor"];
$subject = $_POST["subject"];
$to = $_POST["to"];

try {

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->Mailer = "smtp";
        $mail->SMTPDebug  = 1;
        $mail->SMTPAuth   = TRUE;
        $mail->SMTPSecure = "tls";
        $mail->Port       = 587;
        $mail->Host       = "smtp.gmail.com";//using smtp server
        $mail->Username   = "[email protected]";//the email which will send the email 
        $mail->Password   = "XXXXXXXXXX";//the password

        $mail->IsHTML(true);
        $mail->AddAddress($to, "recipient-name");
        $mail->SetFrom("[email protected]", "from-name");
        $mail->AddReplyTo("[email protected]", "reply-to-name");
        $mail->Subject = $subject;
        $mail->MsgHTML($editor);




        if (!$mail->Send()) {
            echo "Error while sending Email.";
            var_dump($mail);
        } else {
            echo "Email sent successfully";
        }
    }
} catch (Exception $e) {
    echo $e->getMessage();
}
455

Answer

Solution:

You can see your errors by:

error_reporting(E_ALL);

And my sample code is:

<?php
    use PHPMailer\PHPMailer\PHPMailer;
    require 'PHPMailer.php';
    require 'SMTP.php';
    require 'Exception.php';

    $name = $_POST['name'];
    $mailid = $_POST['mail'];
    $mail = new PHPMailer;
    $mail->IsSMTP();
    $mail->SMTPDebug = 0;                   // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';         // Specify main and backup server
    $mail->Port = 587;                      // Set the SMTP port
    $mail->SMTPAuth = true;                 // Enable SMTP authentication
    $mail->Username = '[email protected]';  // SMTP username
    $mail->Password = 'password';           // SMTP password
    $mail->SMTPSecure = 'tls';              // Enable encryption, 'ssl' also accepted

    $mail->From = '[email protected]';
    $mail->FromName = 'name';
    $mail->AddAddress($mailid, $name);       // Name is optional
    $mail->IsHTML(true);                     // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'Here is your message' ;
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
    if (!$mail->Send()) {
       echo 'Message could not be sent.';
       echo 'Mailer Error: ' . $mail->ErrorInfo;
       exit;
    }
    echo 'Message has been sent';
?>
737

Answer

Solution:

If you're stuck with an app hosted on Hostgator, this is what solved my problem. Thanks a lot to the guy who posted the detailed solution. In case the link goes offline one day, there you have the summary:

  • Look for the sendmail path in your server. A simple way to check it, is to temporarily write the following code in a page which only you will access, to read the generated info:<?php phpinfo(); ?>. Open this page, and look forsendmail path. (Then, don't forget to remove this code!)
  • Problem and fix: if your sendmail path is saying only-t -i, then edit your server'sphp.ini and add the following line:sendmail_path = /usr/sbin/sendmail -t -i;

But, after being able to send mail with PHPmail() function, I learned that it sends not authenticated email, what created another issue. The emails were all falling in my Hotmail's junk mail box, and some emails were never delivered, which I guess is related to the fact that they are not authenticated. That's why I decided to switch frommail() toPHPMailer with SMTP, after all.

764

Answer

Solution:

It may be a problem with "From:" $email address in this part of the $headers:

From: \"$name\" <$email>

To try it out, send an email without the headers part, like:

mail('[email protected]', $subject, $message); 

If that is a case, try using an email account that is already created at the system you are trying to send mail from.

681

Answer

Solution:

<?php

$to       = '[email protected]';
$subject  = 'Write your email subject here.';
$message  = '
<html>
<head>
<title>Title here</title>
</head>
<body>
<p>Message here</p>
</body>
</html>
';

// Carriage return type (RFC).
$eol = "\r\n";

$headers  = "Reply-To: Name <[email protected]>".$eol;
$headers .= "Return-Path: Name <[email protected]>".$eol;
$headers .= "From: Name <[email protected]>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/html; charset=iso-8859-1".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;


mail($to, $subject, $message, $headers);

Sending HTML email While sending an email message you can specify a Mime version, content type and character set to send an HTML email.

Example The above example will send an HTML email message to [email protected] You can code this program in such a way that it should receive all content from the user and then it should send an email.

763

Answer

Solution:

What solved this issue for me was that some providers don't allow external recipients when using php mail:

Change the recipient ($recipient) in the code to a local recipient. This means use an email address from the server's domain, for example if your server domain is www.yourdomain.com then the recipient's email should be [email protected] Upload the modified php file and retry. If it's still not working: change the sender ($sender) to a local email (use the same email as used for recipient). Upload the modified php file and retry.

Hope this helps some! https://www.arclab.com/en/kb/php/how-to-test-and-fix-php-mail-function.html

49

Answer

Solution:

I had this problem and found that stripping back the headers helped me to get mail out. So this:

$headers  = "MIME-Version: 1.0;\r\n";
$headers .= "Content-type: text/plain; charset=utf-8;\r\n";
$headers .= "To: ".$recipient."\r\n";
$headers .= "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

became this:

$headers = "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

No need for the To: header.

Mail clients are pretty good at sniffing out URLs and rewriting them as a hyperlink. So I didn't bother writing HTML and specifying text/html in the content-type header. I just threw new lines with \r\n in the message body. I appreciate this isn't the coding purist's approach but it works for what I need it for.

407

Answer

Solution:

There are several possibilities:

  1. You're facing a server problem. The server does not have any mail server. So your mail is not working, because your code is fine and mail is working with type.

  2. You are not getting the posted value. Try your code with a static value.

  3. Use SMTP mails to send mail...

273

Answer

Solution:

Although there are portions of this answer that apply to only to the usage of themail() function itself, many of these troubleshooting steps can be applied to any PHP mailing system.

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.

error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");

See How can I get useful error messages in PHP?this answer for more details on this.

Make sure themail() function is called

It may seem silly but a common error is to forget to actually place themail() function in your code. Make sure it is there and not commented out.

Make sure themail() function is called correctly

bool mail ( string $to, string $subject, string $message [, string $additional_headers [, string $additional_parameters ]] )

The mail function takes three required parameters and optionally a fourth and fifth one. If your call tomail() does not have at least three parameters it will fail.

If your call tomail() does not have the correct parameters in the correct order it will also fail.

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 underlogs. Inside will be error messages the server reported, if any, related to your attempts to send emails.

Check for Port connection failure

Port block is a very common problem which most developers face while integrating their code to deliver emails using SMTP. And, this can be easily traced at the server maillogs (the location of server of mail log can vary from server to server, as explained above). In case you are on a shared hosting server, the ports 25 and 587 remain blocked by default. This block is been purposely done by your hosting provider. This is true even for some of the dedicated servers. When these ports are blocked, try to connect using port 2525. If you find that port is also blocked, then the only solution is to contact your hosting provider to unblock these ports.

Most of the hosting providers block these email ports to protect their network from sending any spam emails.

Use ports 25 or 587 for plain/TLS connections and port 465 for SSL connections. For most users, it is suggested to use port 587 to avoid rate limits set by some hosting providers.

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 right afterwards for concrete failures.

Check themail() return value

The function:

ReturnsTRUE 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 aFALSE 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 you receive aTRUE 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.

SoFALSE will help point you in the right direction whereasTRUE does not necessarily mean your email was sent successfully. This is important to note!

Make sure your hosting provider allows you to send emails and does not limit mail sending

Many shared webhosts, especially free webhosting providers, either do not allow emails to be sent from their servers or limit the amount that can be sent during any given time period. This is due to their efforts to limit spammers from taking advantage of their cheaper services.

If you think your host has emailing limits or blocks the sending of emails, check their FAQs to see if they list any such limitations. Otherwise, you may need to reach out to their support to verify if there are any restrictions in place around the sending of emails.

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" <[email protected]> ).
  • Monitor your abuse accounts, such as[email protected] and[email protected]. 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: [email protected]",
    "Reply-To: [email protected]",
    "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 [email protected]", // missing colon
    "Reply To: [email protected]",      // missing hyphen
    "X-Mailer: "PHP"/" . PHP_VERSION      // bad quotes
);

Don't use a fauxFrom: sender

While the mail must have a From: sender, you may not just use any value. In particular user-supplied sender addresses are a surefire way to get mails blocked:

$headers = array("From: $_POST[contactform_sender_email]"); // No!

Reason: your web or sending mail server is not SPF/DKIM-whitelisted to pretend being responsible for @hotmail or @gmail addresses. It may even silently drop mails withFrom: sender domains it's not configured for.

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 = '[email protected]';
// other variables ....
mail($recipient, $subject, $message, $headers); // $recipient should be $to

Another way to test this is to hard code the recipient value into themail() function call:

mail('[email protected]', $subject, $message, $headers);

This can apply to all of themail() 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 toPOST, make sure you are using$_POST to look for your form values. If you have set it toGET or didn't set it at all, make sure you use$_GET to look for your form values.

Make sure your formaction value points to the correct location

Make sure your formaction attribute contains a value that points to your PHP mailing code.

<form action="send_email.php" method="POST">

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 thelocalhost 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 custommail.log

In addition to your MTA's and PHP's log file, you can enable logging for the 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 http://php.net/manual/en/mail.configuration.php for details. (It's best to enable these options in thephp.ini or.user.ini or.htaccess perhaps.)

Check with a mail testing service

There are various delivery and spamminess checking services you can utilize to test your MTA/webserver setup. Typically you send a mail probe To: their address, then get a delivery report and more concrete failures or analyzations later:

Use a different mailer

PHP's built-inmail() 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:

All of which can be combined with a professional SMTP server/service provider. (Because typical 08/15 shared webhosting plans are hit or miss when it comes to email setup/configurability.)

309

Answer

Solution:

Add a mail header in the mail function:

$header = "From: [email protected]\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);

if($status)
{
    echo '<p>Your mail has been sent!</p>';
} else {
    echo '<p>Something went wrong. Please try again!</p>';
}
815

Answer

Solution:

  1. Always try sending headers in the mail function.
  2. If you are sending mail through localhost then do the SMTP settings for sending mail.
  3. If you are sending mail through a server then check the email sending feature is enabled on your server.
334

Answer

Solution:

If you are using an SMTP configuration for sending your email, try using PHPMailer instead. You can download the library from https://github.com/PHPMailer/PHPMailer.

I created my email sending this way:

function send_mail($email, $recipient_name, $message='')
{
    require("phpmailer/class.phpmailer.php");

    $mail = new PHPMailer();

    $mail->CharSet = "utf-8";
    $mail->IsSMTP();                                      // Set mailer to use SMTP
    $mail->Host = "mail.example.com";  // Specify main and backup server
    $mail->SMTPAuth = true;     // Turn on SMTP authentication
    $mail->Username = "myusername";  // SMTP username
    $mail->Password = "[email protected]"; // SMTP password

    $mail->From = "[email protected]";
    $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');
    $mail->addAttachment('files/file.xlsx');

    if(!$mail->Send())
    {
       echo "Message could not be sent. <p>";
       echo "Mailer Error: " . $mail->ErrorInfo;
       exit;
    }

    echo "Message has been sent";
}
485

Answer

Solution:

Just add some headers before sending mail:

<?php 
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com'; 
$to = '[email protected]'; 
$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: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

And one more thing. Themail() function is not working in localhost. Upload your code to a server and try.

78

Answer

Solution:

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('[email protected]', $subject, $message, $headers)

Use'' and not"".

This code works, but the email was received with half an hour lag.

523

Answer

Solution:

Mostly themail() function is disabled in shared hosting. A better option is to use SMTP. The best option would be Gmail or SendGrid.


SMTPconfig.php

<?php 
    $SmtpServer="smtp.*.*";
    $SmtpPort="2525"; //default
    $SmtpUser="***";
    $SmtpPass="***";
?>

SMTPmail.php

<?php
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;
        }
        else
        {
            $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");
            $talk["res"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpUser."\r\n");
            $talk["user"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpPass."\r\n");
            $talk["pass"]=fgets($SMTPIN,256);
            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");
            $talk["send"]=fgets($SMTPIN,256);
            //CLOSE CONNECTION AND EXIT ... 
            fputs ($SMTPIN, "QUIT\r\n"); 
            fclose($SMTPIN); 
            // 
        } 
        return $talk;
    } 
}
?>

contact_email.php

<?php 
include('SMTPconfig.php');
include('SMTPmail.php');
if($_SERVER["REQUEST_METHOD"] == "POST")
{
    $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();
}
?>
99

Answer

Solution:

If you only use themail()function, you need to complete the configuration file.

You need to open the mail expansion, and set theSMTP smtp_port and so on, and most important, your username and your password. Without that, mail cannot be sent. Also, you can use thePHPMail class to send.

355

Answer

Solution:

Try these two things separately and together:

  1. remove theif($_POST['submit']){}
  2. remove$from (just my gut)
554

Answer

Solution:

I think this should do the trick. I just added anif(isset and added concatenation to the variables in the body to separate PHP from HTML.

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: yoursite.com'; 
    $to = '[email protected]'; 
    $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>';
    } 
    else 
    { 
        echo '<p>Something went wrong, go back and try again!</p>'; 
    }
}

?>
761

Answer

Solution:

For anyone who finds this going forward, I would not recommend usingmail. There's some answers that touch on this, but not the why of it.

PHP'smail 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 frommail. 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 usemail to ultimately send the mail, but I would strongly recommend you not do that).

This means 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 callingisSMTP()), you can get a detailed transcript of the SMTP conversation using theSMTPDebug 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. Withmail 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).

816

Answer

Solution:

$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 class="page_speed_1833695416">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>";
}
811

Answer

Solution:

You can use config email by CodeIgniter. For example, using SMTP (simple way):

$config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'mail.domain.com', // Your SMTP host
        'smtp_port' => 26, // Default port for SMTP
        'smtp_user' => '[email protected]',
        'smtp_pass' => 'password',
        'mailtype' => 'html',
        'charset' => 'iso-8859-1',
        'wordwrap' => TRUE
);
$message = 'Your msg';
$this->load->library('email', $config);
$this->email->from('[email protected]', 'Title');
$this->email->to('[email protected]');
$this->email->subject('Header');
$this->email->message($message);

if($this->email->send()) 
{
   // Conditional true
}

It works for me!

193

Answer

Solution:

Try this

if ($_POST['submit']) {
    $success= mail($to, $subject, $body, $from);
    if($success)
    { 
        echo '
        <p>Your message has been sent!</p>
        ';
    } else { 
        echo '
        <p>Something went wrong, go back and try again!</p>
        '; 
    }
}
993

Answer

Solution:

Maybe the problem is the configuration of the mail server. To avoid this type of problems or you do not have to worry about the mail server problem, I recommend you use PHPMailer.

It is a plugin that has everything necessary to send mail, and the only thing you have to take into account is to have the SMTP port (Port: 25 and 465), enabled.

require_once 'PHPMailer/PHPMailer.php';
require_once '/servicios/PHPMailer/SMTP.php';
require_once '/servicios/PHPMailer/Exception.php';

$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
    //Server settings
    $mail->SMTPDebug = 0;
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = '[email protected]';
    $mail->Password = 'contrasenia';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;

    // Recipients
    $mail->setFrom('[email protected]', 'my name');
    $mail->addAddress('[email protected]');

    // Attachments
    $mail->addAttachment('optional file');         // Add files, is optional

    // Content
    $mail->isHTML(true);// Set email format to HTML
    $mail->Subject = utf8_decode("subject");
    $mail->Body    = utf8_decode("mail content");
    $mail->AltBody = '';
    $mail->send();
}
catch (Exception $e) {
    $error = $mail->ErrorInfo;
}
975

Answer

Solution:

First of all, you might have too many parameters for the mail() function... You are able to have of maximum of five,mail(to, subject, message, headers, parameters);

As far as the$from variable goes, that should automatically come from your webhost if your using the Linux cPanel. It automatically comes from your cPanel username and IP address.

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com';
$to = '[email protected]';
$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.

Themail($to, $subject, $message, etc.) in that order, or else there is a chance of it not working.

761

Answer

Solution:

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 www.AceITLab.com, 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.

636

Answer

Solution:

Make sure you have Sendmail installed in your server.

If you have checked your code and verified that there is nothing wrong there, go to /var/mail and check whether that folder is empty.

If it is empty, you will need to do a:

sudo apt-get install sendmail

if you are on an Ubuntu server.

708

Answer

Solution:

For those who do not want to use external mailers and want to mail() on a dedicated Linux server.

The way, how PHP mails, is described inphp.ini in section[mail function].

Parametersendmail-path describes how sendmail is called. The default value issendmail -t -i, so if you get a workingsendmail -t -i < message.txt in the Linux console - you will be done. You could also addmail.log to debug and be sure mail() is really called.

Different MTAs can implementsendmail. They just make a symbolic link to their binaries on that name. For example, in Debian the default is Postfix. Configure your MTA to send mail and test it from the console withsendmail -v -t -i < message.txt. Filemessage.txt should contain all headers of a message and a body, destination address for the envelope will be taken from theTo: header. Example:

From: [email protected]
To: [email protected]
Subject: Test mail via sendmail.

Text body.

I prefer to use ssmtp as MTA because it is simple and does not require running a daemon with opened ports. ssmtp fits only for sending mail from localhost. It also can send authenticated email via your account on a public mail service. Install ssmtp and edit configuration file/etc/ssmtp/ssmtp.conf. To be able also to receive local system mail to Unix accounts (alerts to root from cron jobs, for example) configure/etc/ssmtp/revaliases file.

Here is my configuration for my account on Yandex mail:

[email protected]
mailhub=smtp.yandex.ru:465
FromLineOverride=YES
UseTLS=YES
[email protected]
AuthPass=password
439

Answer

Solution:

Sendmail installation for Debian 10.0.0 ('Buster') was in fact trivial!

php.ini

[mail function]
sendmail_path=/usr/sbin/sendmail -t -i
; (Other directives are mostly windows)

Standard sendmail package install (allowing 'send'):

su -                                        # Install as user 'root'
dpkg --list                                 # Is install necessary?
apt-get install sendmail sendmail-cf m4     # Note multiple package selection
sendmailconfig                              # Respond all 'Y' for new install

Miscellaneous useful commands:

which sendmail                              # /usr/sbin/sendmail
which sendmailconfig                        # /usr/sbin/sendmailconfig
man sendmail                                # Documentation
systemctl restart sendmail                  # As and when required

Verification (of ability to send)

echo "Subject: sendmail test" | sendmail -v <yourEmail>@gmail.com

The above took about 5 minutes. Then I wasted 5 hours... Don't forget to check your spam folder!

225

Answer

Solution:

If you are running this code on a local server (i.e your computer for development purposes) it won't send the email to the recipient. It will create a.txt file in a folder namedmailoutput.

In the case if you are using a free hosing service, like000webhost orhostinger, those service providers disable themail() 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):

<?php
    $to      = '[email protected]';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: [email protected]' . "\r\n" .
        'Reply-To: [email protected]' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
?>
256

Answer

Solution:

You can use thePHPMailer and it works perfectly,here's a code example:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/phpmailer/phpmailer/src/Exception.php';
require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/phpmailer/src/SMTP.php';
$editor = $_POST["editor"];
$subject = $_POST["subject"];
$to = $_POST["to"];

try {

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->Mailer = "smtp";
        $mail->SMTPDebug  = 1;
        $mail->SMTPAuth   = TRUE;
        $mail->SMTPSecure = "tls";
        $mail->Port       = 587;
        $mail->Host       = "smtp.gmail.com";//using smtp server
        $mail->Username   = "[email protected]";//the email which will send the email 
        $mail->Password   = "XXXXXXXXXX";//the password

        $mail->IsHTML(true);
        $mail->AddAddress($to, "recipient-name");
        $mail->SetFrom("[email protected]", "from-name");
        $mail->AddReplyTo("[email protected]", "reply-to-name");
        $mail->Subject = $subject;
        $mail->MsgHTML($editor);




        if (!$mail->Send()) {
            echo "Error while sending Email.";
            var_dump($mail);
        } else {
            echo "Email sent successfully";
        }
    }
} catch (Exception $e) {
    echo $e->getMessage();
}
278

Answer

Solution:

You can see your errors by:

error_reporting(E_ALL);

And my sample code is:

<?php
    use PHPMailer\PHPMailer\PHPMailer;
    require 'PHPMailer.php';
    require 'SMTP.php';
    require 'Exception.php';

    $name = $_POST['name'];
    $mailid = $_POST['mail'];
    $mail = new PHPMailer;
    $mail->IsSMTP();
    $mail->SMTPDebug = 0;                   // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';         // Specify main and backup server
    $mail->Port = 587;                      // Set the SMTP port
    $mail->SMTPAuth = true;                 // Enable SMTP authentication
    $mail->Username = '[email protected]';  // SMTP username
    $mail->Password = 'password';           // SMTP password
    $mail->SMTPSecure = 'tls';              // Enable encryption, 'ssl' also accepted

    $mail->From = '[email protected]';
    $mail->FromName = 'name';
    $mail->AddAddress($mailid, $name);       // Name is optional
    $mail->IsHTML(true);                     // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'Here is your message' ;
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
    if (!$mail->Send()) {
       echo 'Message could not be sent.';
       echo 'Mailer Error: ' . $mail->ErrorInfo;
       exit;
    }
    echo 'Message has been sent';
?>
640

Answer

Solution:

If you're stuck with an app hosted on Hostgator, this is what solved my problem. Thanks a lot to the guy who posted the detailed solution. In case the link goes offline one day, there you have the summary:

  • Look for the sendmail path in your server. A simple way to check it, is to temporarily write the following code in a page which only you will access, to read the generated info:<?php phpinfo(); ?>. Open this page, and look forsendmail path. (Then, don't forget to remove this code!)
  • Problem and fix: if your sendmail path is saying only-t -i, then edit your server'sphp.ini and add the following line:sendmail_path = /usr/sbin/sendmail -t -i;

But, after being able to send mail with PHPmail() function, I learned that it sends not authenticated email, what created another issue. The emails were all falling in my Hotmail's junk mail box, and some emails were never delivered, which I guess is related to the fact that they are not authenticated. That's why I decided to switch frommail() toPHPMailer with SMTP, after all.

300

Answer

Solution:

It may be a problem with "From:" $email address in this part of the $headers:

From: \"$name\" <$email>

To try it out, send an email without the headers part, like:

mail('[email protected]', $subject, $message); 

If that is a case, try using an email account that is already created at the system you are trying to send mail from.

173

Answer

Solution:

<?php

$to       = '[email protected]';
$subject  = 'Write your email subject here.';
$message  = '
<html>
<head>
<title>Title here</title>
</head>
<body>
<p>Message here</p>
</body>
</html>
';

// Carriage return type (RFC).
$eol = "\r\n";

$headers  = "Reply-To: Name <[email protected]>".$eol;
$headers .= "Return-Path: Name <[email protected]>".$eol;
$headers .= "From: Name <[email protected]>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/html; charset=iso-8859-1".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;


mail($to, $subject, $message, $headers);

Sending HTML email While sending an email message you can specify a Mime version, content type and character set to send an HTML email.

Example The above example will send an HTML email message to [email protected] You can code this program in such a way that it should receive all content from the user and then it should send an email.

143

Answer

Solution:

What solved this issue for me was that some providers don't allow external recipients when using php mail:

Change the recipient ($recipient) in the code to a local recipient. This means use an email address from the server's domain, for example if your server domain is www.yourdomain.com then the recipient's email should be [email protected] Upload the modified php file and retry. If it's still not working: change the sender ($sender) to a local email (use the same email as used for recipient). Upload the modified php file and retry.

Hope this helps some! https://www.arclab.com/en/kb/php/how-to-test-and-fix-php-mail-function.html

740

Answer

Solution:

I had this problem and found that stripping back the headers helped me to get mail out. So this:

$headers  = "MIME-Version: 1.0;\r\n";
$headers .= "Content-type: text/plain; charset=utf-8;\r\n";
$headers .= "To: ".$recipient."\r\n";
$headers .= "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

became this:

$headers = "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

No need for the To: header.

Mail clients are pretty good at sniffing out URLs and rewriting them as a hyperlink. So I didn't bother writing HTML and specifying text/html in the content-type header. I just threw new lines with \r\n in the message body. I appreciate this isn't the coding purist's approach but it works for what I need it for.

153

Answer

Solution:

There are several possibilities:

  1. You're facing a server problem. The server does not have any mail server. So your mail is not working, because your code is fine and mail is working with type.

  2. You are not getting the posted value. Try your code with a static value.

  3. Use SMTP mails to send mail...

264

Answer

Solution:

Although there are portions of this answer that apply to only to the usage of themail() function itself, many of these troubleshooting steps can be applied to any PHP mailing system.

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.

error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");

See How can I get useful error messages in PHP?this answer for more details on this.

Make sure themail() function is called

It may seem silly but a common error is to forget to actually place themail() function in your code. Make sure it is there and not commented out.

Make sure themail() function is called correctly

bool mail ( string $to, string $subject, string $message [, string $additional_headers [, string $additional_parameters ]] )

The mail function takes three required parameters and optionally a fourth and fifth one. If your call tomail() does not have at least three parameters it will fail.

If your call tomail() does not have the correct parameters in the correct order it will also fail.

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 underlogs. Inside will be error messages the server reported, if any, related to your attempts to send emails.

Check for Port connection failure

Port block is a very common problem which most developers face while integrating their code to deliver emails using SMTP. And, this can be easily traced at the server maillogs (the location of server of mail log can vary from server to server, as explained above). In case you are on a shared hosting server, the ports 25 and 587 remain blocked by default. This block is been purposely done by your hosting provider. This is true even for some of the dedicated servers. When these ports are blocked, try to connect using port 2525. If you find that port is also blocked, then the only solution is to contact your hosting provider to unblock these ports.

Most of the hosting providers block these email ports to protect their network from sending any spam emails.

Use ports 25 or 587 for plain/TLS connections and port 465 for SSL connections. For most users, it is suggested to use port 587 to avoid rate limits set by some hosting providers.

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 right afterwards for concrete failures.

Check themail() return value

The function:

ReturnsTRUE 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 aFALSE 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 you receive aTRUE 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.

SoFALSE will help point you in the right direction whereasTRUE does not necessarily mean your email was sent successfully. This is important to note!

Make sure your hosting provider allows you to send emails and does not limit mail sending

Many shared webhosts, especially free webhosting providers, either do not allow emails to be sent from their servers or limit the amount that can be sent during any given time period. This is due to their efforts to limit spammers from taking advantage of their cheaper services.

If you think your host has emailing limits or blocks the sending of emails, check their FAQs to see if they list any such limitations. Otherwise, you may need to reach out to their support to verify if there are any restrictions in place around the sending of emails.

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" <[email protected]> ).
  • Monitor your abuse accounts, such as[email protected] and[email protected]. 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: [email protected]",
    "Reply-To: [email protected]",
    "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 [email protected]", // missing colon
    "Reply To: [email protected]",      // missing hyphen
    "X-Mailer: "PHP"/" . PHP_VERSION      // bad quotes
);

Don't use a fauxFrom: sender

While the mail must have a From: sender, you may not just use any value. In particular user-supplied sender addresses are a surefire way to get mails blocked:

$headers = array("From: $_POST[contactform_sender_email]"); // No!

Reason: your web or sending mail server is not SPF/DKIM-whitelisted to pretend being responsible for @hotmail or @gmail addresses. It may even silently drop mails withFrom: sender domains it's not configured for.

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 = '[email protected]';
// other variables ....
mail($recipient, $subject, $message, $headers); // $recipient should be $to

Another way to test this is to hard code the recipient value into themail() function call:

mail('[email protected]', $subject, $message, $headers);

This can apply to all of themail() 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 toPOST, make sure you are using$_POST to look for your form values. If you have set it toGET or didn't set it at all, make sure you use$_GET to look for your form values.

Make sure your formaction value points to the correct location

Make sure your formaction attribute contains a value that points to your PHP mailing code.

<form action="send_email.php" method="POST">

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 thelocalhost 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 custommail.log

In addition to your MTA's and PHP's log file, you can enable logging for the 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 http://php.net/manual/en/mail.configuration.php for details. (It's best to enable these options in thephp.ini or.user.ini or.htaccess perhaps.)

Check with a mail testing service

There are various delivery and spamminess checking services you can utilize to test your MTA/webserver setup. Typically you send a mail probe To: their address, then get a delivery report and more concrete failures or analyzations later:

Use a different mailer

PHP's built-inmail() 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:

All of which can be combined with a professional SMTP server/service provider. (Because typical 08/15 shared webhosting plans are hit or miss when it comes to email setup/configurability.)

577

Answer

Solution:

Add a mail header in the mail function:

$header = "From: [email protected]\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);

if($status)
{
    echo '<p>Your mail has been sent!</p>';
} else {
    echo '<p>Something went wrong. Please try again!</p>';
}
403

Answer

Solution:

  1. Always try sending headers in the mail function.
  2. If you are sending mail through localhost then do the SMTP settings for sending mail.
  3. If you are sending mail through a server then check the email sending feature is enabled on your server.
381

Answer

Solution:

If you are using an SMTP configuration for sending your email, try using PHPMailer instead. You can download the library from https://github.com/PHPMailer/PHPMailer.

I created my email sending this way:

function send_mail($email, $recipient_name, $message='')
{
    require("phpmailer/class.phpmailer.php");

    $mail = new PHPMailer();

    $mail->CharSet = "utf-8";
    $mail->IsSMTP();                                      // Set mailer to use SMTP
    $mail->Host = "mail.example.com";  // Specify main and backup server
    $mail->SMTPAuth = true;     // Turn on SMTP authentication
    $mail->Username = "myusername";  // SMTP username
    $mail->Password = "[email protected]"; // SMTP password

    $mail->From = "[email protected]";
    $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');
    $mail->addAttachment('files/file.xlsx');

    if(!$mail->Send())
    {
       echo "Message could not be sent. <p>";
       echo "Mailer Error: " . $mail->ErrorInfo;
       exit;
    }

    echo "Message has been sent";
}
32

Answer

Solution:

Just add some headers before sending mail:

<?php 
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com'; 
$to = '[email protected]'; 
$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: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

And one more thing. Themail() function is not working in localhost. Upload your code to a server and try.

445

Answer

Solution:

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('[email protected]', $subject, $message, $headers)

Use'' and not"".

This code works, but the email was received with half an hour lag.

432

Answer

Solution:

Mostly themail() function is disabled in shared hosting. A better option is to use SMTP. The best option would be Gmail or SendGrid.


SMTPconfig.php

<?php 
    $SmtpServer="smtp.*.*";
    $SmtpPort="2525"; //default
    $SmtpUser="***";
    $SmtpPass="***";
?>

SMTPmail.php

<?php
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;
        }
        else
        {
            $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");
            $talk["res"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpUser."\r\n");
            $talk["user"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpPass."\r\n");
            $talk["pass"]=fgets($SMTPIN,256);
            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");
            $talk["send"]=fgets($SMTPIN,256);
            //CLOSE CONNECTION AND EXIT ... 
            fputs ($SMTPIN, "QUIT\r\n"); 
            fclose($SMTPIN); 
            // 
        } 
        return $talk;
    } 
}
?>

contact_email.php

<?php 
include('SMTPconfig.php');
include('SMTPmail.php');
if($_SERVER["REQUEST_METHOD"] == "POST")
{
    $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();
}
?>
60

Answer

Solution:

If you only use themail()function, you need to complete the configuration file.

You need to open the mail expansion, and set theSMTP smtp_port and so on, and most important, your username and your password. Without that, mail cannot be sent. Also, you can use thePHPMail class to send.

18

Answer

Solution:

Try these two things separately and together:

  1. remove theif($_POST['submit']){}
  2. remove$from (just my gut)
258

Answer

Solution:

I think this should do the trick. I just added anif(isset and added concatenation to the variables in the body to separate PHP from HTML.

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: yoursite.com'; 
    $to = '[email protected]'; 
    $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>';
    } 
    else 
    { 
        echo '<p>Something went wrong, go back and try again!</p>'; 
    }
}

?>
909

Answer

Solution:

For anyone who finds this going forward, I would not recommend usingmail. There's some answers that touch on this, but not the why of it.

PHP'smail 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 frommail. 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 usemail to ultimately send the mail, but I would strongly recommend you not do that).

This means 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 callingisSMTP()), you can get a detailed transcript of the SMTP conversation using theSMTPDebug 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. Withmail 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).

167

Answer

Solution:

$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 class="page_speed_1833695416">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>";
}
995

Answer

Solution:

You can use config email by CodeIgniter. For example, using SMTP (simple way):

$config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'mail.domain.com', // Your SMTP host
        'smtp_port' => 26, // Default port for SMTP
        'smtp_user' => '[email protected]',
        'smtp_pass' => 'password',
        'mailtype' => 'html',
        'charset' => 'iso-8859-1',
        'wordwrap' => TRUE
);
$message = 'Your msg';
$this->load->library('email', $config);
$this->email->from('[email protected]', 'Title');
$this->email->to('[email protected]');
$this->email->subject('Header');
$this->email->message($message);

if($this->email->send()) 
{
   // Conditional true
}

It works for me!

906

Answer

Solution:

Try this

if ($_POST['submit']) {
    $success= mail($to, $subject, $body, $from);
    if($success)
    { 
        echo '
        <p>Your message has been sent!</p>
        ';
    } else { 
        echo '
        <p>Something went wrong, go back and try again!</p>
        '; 
    }
}
762

Answer

Solution:

Maybe the problem is the configuration of the mail server. To avoid this type of problems or you do not have to worry about the mail server problem, I recommend you use PHPMailer.

It is a plugin that has everything necessary to send mail, and the only thing you have to take into account is to have the SMTP port (Port: 25 and 465), enabled.

require_once 'PHPMailer/PHPMailer.php';
require_once '/servicios/PHPMailer/SMTP.php';
require_once '/servicios/PHPMailer/Exception.php';

$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
    //Server settings
    $mail->SMTPDebug = 0;
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = '[email protected]';
    $mail->Password = 'contrasenia';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;

    // Recipients
    $mail->setFrom('[email protected]', 'my name');
    $mail->addAddress('[email protected]');

    // Attachments
    $mail->addAttachment('optional file');         // Add files, is optional

    // Content
    $mail->isHTML(true);// Set email format to HTML
    $mail->Subject = utf8_decode("subject");
    $mail->Body    = utf8_decode("mail content");
    $mail->AltBody = '';
    $mail->send();
}
catch (Exception $e) {
    $error = $mail->ErrorInfo;
}
670

Answer

Solution:

First of all, you might have too many parameters for the mail() function... You are able to have of maximum of five,mail(to, subject, message, headers, parameters);

As far as the$from variable goes, that should automatically come from your webhost if your using the Linux cPanel. It automatically comes from your cPanel username and IP address.

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com';
$to = '[email protected]';
$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.

Themail($to, $subject, $message, etc.) in that order, or else there is a chance of it not working.

514

Answer

Solution:

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 www.AceITLab.com, 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.

134

Answer

Solution:

Make sure you have Sendmail installed in your server.

If you have checked your code and verified that there is nothing wrong there, go to /var/mail and check whether that folder is empty.

If it is empty, you will need to do a:

sudo apt-get install sendmail

if you are on an Ubuntu server.

164

Answer

Solution:

For those who do not want to use external mailers and want to mail() on a dedicated Linux server.

The way, how PHP mails, is described inphp.ini in section[mail function].

Parametersendmail-path describes how sendmail is called. The default value issendmail -t -i, so if you get a workingsendmail -t -i < message.txt in the Linux console - you will be done. You could also addmail.log to debug and be sure mail() is really called.

Different MTAs can implementsendmail. They just make a symbolic link to their binaries on that name. For example, in Debian the default is Postfix. Configure your MTA to send mail and test it from the console withsendmail -v -t -i < message.txt. Filemessage.txt should contain all headers of a message and a body, destination address for the envelope will be taken from theTo: header. Example:

From: [email protected]
To: [email protected]
Subject: Test mail via sendmail.

Text body.

I prefer to use ssmtp as MTA because it is simple and does not require running a daemon with opened ports. ssmtp fits only for sending mail from localhost. It also can send authenticated email via your account on a public mail service. Install ssmtp and edit configuration file/etc/ssmtp/ssmtp.conf. To be able also to receive local system mail to Unix accounts (alerts to root from cron jobs, for example) configure/etc/ssmtp/revaliases file.

Here is my configuration for my account on Yandex mail:

[email protected]
mailhub=smtp.yandex.ru:465
FromLineOverride=YES
UseTLS=YES
[email protected]
AuthPass=password
406

Answer

Solution:

Sendmail installation for Debian 10.0.0 ('Buster') was in fact trivial!

php.ini

[mail function]
sendmail_path=/usr/sbin/sendmail -t -i
; (Other directives are mostly windows)

Standard sendmail package install (allowing 'send'):

su -                                        # Install as user 'root'
dpkg --list                                 # Is install necessary?
apt-get install sendmail sendmail-cf m4     # Note multiple package selection
sendmailconfig                              # Respond all 'Y' for new install

Miscellaneous useful commands:

which sendmail                              # /usr/sbin/sendmail
which sendmailconfig                        # /usr/sbin/sendmailconfig
man sendmail                                # Documentation
systemctl restart sendmail                  # As and when required

Verification (of ability to send)

echo "Subject: sendmail test" | sendmail -v <yourEmail>@gmail.com

The above took about 5 minutes. Then I wasted 5 hours... Don't forget to check your spam folder!

318

Answer

Solution:

If you are running this code on a local server (i.e your computer for development purposes) it won't send the email to the recipient. It will create a.txt file in a folder namedmailoutput.

In the case if you are using a free hosing service, like000webhost orhostinger, those service providers disable themail() 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):

<?php
    $to      = '[email protected]';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: [email protected]' . "\r\n" .
        'Reply-To: [email protected]' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
?>
985

Answer

Solution:

You can use thePHPMailer and it works perfectly,here's a code example:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/phpmailer/phpmailer/src/Exception.php';
require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/phpmailer/src/SMTP.php';
$editor = $_POST["editor"];
$subject = $_POST["subject"];
$to = $_POST["to"];

try {

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->Mailer = "smtp";
        $mail->SMTPDebug  = 1;
        $mail->SMTPAuth   = TRUE;
        $mail->SMTPSecure = "tls";
        $mail->Port       = 587;
        $mail->Host       = "smtp.gmail.com";//using smtp server
        $mail->Username   = "[email protected]";//the email which will send the email 
        $mail->Password   = "XXXXXXXXXX";//the password

        $mail->IsHTML(true);
        $mail->AddAddress($to, "recipient-name");
        $mail->SetFrom("[email protected]", "from-name");
        $mail->AddReplyTo("[email protected]", "reply-to-name");
        $mail->Subject = $subject;
        $mail->MsgHTML($editor);




        if (!$mail->Send()) {
            echo "Error while sending Email.";
            var_dump($mail);
        } else {
            echo "Email sent successfully";
        }
    }
} catch (Exception $e) {
    echo $e->getMessage();
}
89

Answer

Solution:

You can see your errors by:

error_reporting(E_ALL);

And my sample code is:

<?php
    use PHPMailer\PHPMailer\PHPMailer;
    require 'PHPMailer.php';
    require 'SMTP.php';
    require 'Exception.php';

    $name = $_POST['name'];
    $mailid = $_POST['mail'];
    $mail = new PHPMailer;
    $mail->IsSMTP();
    $mail->SMTPDebug = 0;                   // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';         // Specify main and backup server
    $mail->Port = 587;                      // Set the SMTP port
    $mail->SMTPAuth = true;                 // Enable SMTP authentication
    $mail->Username = '[email protected]';  // SMTP username
    $mail->Password = 'password';           // SMTP password
    $mail->SMTPSecure = 'tls';              // Enable encryption, 'ssl' also accepted

    $mail->From = '[email protected]';
    $mail->FromName = 'name';
    $mail->AddAddress($mailid, $name);       // Name is optional
    $mail->IsHTML(true);                     // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'Here is your message' ;
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
    if (!$mail->Send()) {
       echo 'Message could not be sent.';
       echo 'Mailer Error: ' . $mail->ErrorInfo;
       exit;
    }
    echo 'Message has been sent';
?>
887

Answer

Solution:

If you're stuck with an app hosted on Hostgator, this is what solved my problem. Thanks a lot to the guy who posted the detailed solution. In case the link goes offline one day, there you have the summary:

  • Look for the sendmail path in your server. A simple way to check it, is to temporarily write the following code in a page which only you will access, to read the generated info:<?php phpinfo(); ?>. Open this page, and look forsendmail path. (Then, don't forget to remove this code!)
  • Problem and fix: if your sendmail path is saying only-t -i, then edit your server'sphp.ini and add the following line:sendmail_path = /usr/sbin/sendmail -t -i;

But, after being able to send mail with PHPmail() function, I learned that it sends not authenticated email, what created another issue. The emails were all falling in my Hotmail's junk mail box, and some emails were never delivered, which I guess is related to the fact that they are not authenticated. That's why I decided to switch frommail() toPHPMailer with SMTP, after all.

494

Answer

Solution:

It may be a problem with "From:" $email address in this part of the $headers:

From: \"$name\" <$email>

To try it out, send an email without the headers part, like:

mail('[email protected]', $subject, $message); 

If that is a case, try using an email account that is already created at the system you are trying to send mail from.

827

Answer

Solution:

<?php

$to       = '[email protected]';
$subject  = 'Write your email subject here.';
$message  = '
<html>
<head>
<title>Title here</title>
</head>
<body>
<p>Message here</p>
</body>
</html>
';

// Carriage return type (RFC).
$eol = "\r\n";

$headers  = "Reply-To: Name <[email protected]>".$eol;
$headers .= "Return-Path: Name <[email protected]>".$eol;
$headers .= "From: Name <[email protected]>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/html; charset=iso-8859-1".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;


mail($to, $subject, $message, $headers);

Sending HTML email While sending an email message you can specify a Mime version, content type and character set to send an HTML email.

Example The above example will send an HTML email message to [email protected] You can code this program in such a way that it should receive all content from the user and then it should send an email.

410

Answer

Solution:

What solved this issue for me was that some providers don't allow external recipients when using php mail:

Change the recipient ($recipient) in the code to a local recipient. This means use an email address from the server's domain, for example if your server domain is www.yourdomain.com then the recipient's email should be [email protected] Upload the modified php file and retry. If it's still not working: change the sender ($sender) to a local email (use the same email as used for recipient). Upload the modified php file and retry.

Hope this helps some! https://www.arclab.com/en/kb/php/how-to-test-and-fix-php-mail-function.html

646

Answer

Solution:

I had this problem and found that stripping back the headers helped me to get mail out. So this:

$headers  = "MIME-Version: 1.0;\r\n";
$headers .= "Content-type: text/plain; charset=utf-8;\r\n";
$headers .= "To: ".$recipient."\r\n";
$headers .= "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

became this:

$headers = "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";

No need for the To: header.

Mail clients are pretty good at sniffing out URLs and rewriting them as a hyperlink. So I didn't bother writing HTML and specifying text/html in the content-type header. I just threw new lines with \r\n in the message body. I appreciate this isn't the coding purist's approach but it works for what I need it for.

493

Answer

Solution:

There are several possibilities:

  1. You're facing a server problem. The server does not have any mail server. So your mail is not working, because your code is fine and mail is working with type.

  2. You are not getting the posted value. Try your code with a static value.

  3. Use SMTP mails to send mail...

922

Answer

Solution:

Although there are portions of this answer that apply to only to the usage of themail() function itself, many of these troubleshooting steps can be applied to any PHP mailing system.

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.

error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");

See How can I get useful error messages in PHP?this answer for more details on this.

Make sure themail() function is called

It may seem silly but a common error is to forget to actually place themail() function in your code. Make sure it is there and not commented out.

Make sure themail() function is called correctly

bool mail ( string $to, string $subject, string $message [, string $additional_headers [, string $additional_parameters ]] )

The mail function takes three required parameters and optionally a fourth and fifth one. If your call tomail() does not have at least three parameters it will fail.

If your call tomail() does not have the correct parameters in the correct order it will also fail.

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 underlogs. Inside will be error messages the server reported, if any, related to your attempts to send emails.

Check for Port connection failure

Port block is a very common problem which most developers face while integrating their code to deliver emails using SMTP. And, this can be easily traced at the server maillogs (the location of server of mail log can vary from server to server, as explained above). In case you are on a shared hosting server, the ports 25 and 587 remain blocked by default. This block is been purposely done by your hosting provider. This is true even for some of the dedicated servers. When these ports are blocked, try to connect using port 2525. If you find that port is also blocked, then the only solution is to contact your hosting provider to unblock these ports.

Most of the hosting providers block these email ports to protect their network from sending any spam emails.

Use ports 25 or 587 for plain/TLS connections and port 465 for SSL connections. For most users, it is suggested to use port 587 to avoid rate limits set by some hosting providers.

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 right afterwards for concrete failures.

Check themail() return value

The function:

ReturnsTRUE 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 aFALSE 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 you receive aTRUE 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.

SoFALSE will help point you in the right direction whereasTRUE does not necessarily mean your email was sent successfully. This is important to note!

Make sure your hosting provider allows you to send emails and does not limit mail sending

Many shared webhosts, especially free webhosting providers, either do not allow emails to be sent from their servers or limit the amount that can be sent during any given time period. This is due to their efforts to limit spammers from taking advantage of their cheaper services.

If you think your host has emailing limits or blocks the sending of emails, check their FAQs to see if they list any such limitations. Otherwise, you may need to reach out to their support to verify if there are any restrictions in place around the sending of emails.

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" <[email protected]> ).
  • Monitor your abuse accounts, such as[email protected] and[email protected]. 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: [email protected]",
    "Reply-To: [email protected]",
    "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 [email protected]", // missing colon
    "Reply To: [email protected]",      // missing hyphen
    "X-Mailer: "PHP"/" . PHP_VERSION      // bad quotes
);

Don't use a fauxFrom: sender

While the mail must have a From: sender, you may not just use any value. In particular user-supplied sender addresses are a surefire way to get mails blocked:

$headers = array("From: $_POST[contactform_sender_email]"); // No!

Reason: your web or sending mail server is not SPF/DKIM-whitelisted to pretend being responsible for @hotmail or @gmail addresses. It may even silently drop mails withFrom: sender domains it's not configured for.

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 = '[email protected]';
// other variables ....
mail($recipient, $subject, $message, $headers); // $recipient should be $to

Another way to test this is to hard code the recipient value into themail() function call:

mail('[email protected]', $subject, $message, $headers);

This can apply to all of themail() 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 toPOST, make sure you are using$_POST to look for your form values. If you have set it toGET or didn't set it at all, make sure you use$_GET to look for your form values.

Make sure your formaction value points to the correct location

Make sure your formaction attribute contains a value that points to your PHP mailing code.

<form action="send_email.php" method="POST">

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 thelocalhost 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 custommail.log

In addition to your MTA's and PHP's log file, you can enable logging for the 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 http://php.net/manual/en/mail.configuration.php for details. (It's best to enable these options in thephp.ini or.user.ini or.htaccess perhaps.)

Check with a mail testing service

There are various delivery and spamminess checking services you can utilize to test your MTA/webserver setup. Typically you send a mail probe To: their address, then get a delivery report and more concrete failures or analyzations later:

Use a different mailer

PHP's built-inmail() 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:

All of which can be combined with a professional SMTP server/service provider. (Because typical 08/15 shared webhosting plans are hit or miss when it comes to email setup/configurability.)

218

Answer

Solution:

Add a mail header in the mail function:

$header = "From: [email protected]\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);

if($status)
{
    echo '<p>Your mail has been sent!</p>';
} else {
    echo '<p>Something went wrong. Please try again!</p>';
}
45

Answer

Solution:

  1. Always try sending headers in the mail function.
  2. If you are sending mail through localhost then do the SMTP settings for sending mail.
  3. If you are sending mail through a server then check the email sending feature is enabled on your server.
805

Answer

Solution:

If you are using an SMTP configuration for sending your email, try using PHPMailer instead. You can download the library from https://github.com/PHPMailer/PHPMailer.

I created my email sending this way:

function send_mail($email, $recipient_name, $message='')
{
    require("phpmailer/class.phpmailer.php");

    $mail = new PHPMailer();

    $mail->CharSet = "utf-8";
    $mail->IsSMTP();                                      // Set mailer to use SMTP
    $mail->Host = "mail.example.com";  // Specify main and backup server
    $mail->SMTPAuth = true;     // Turn on SMTP authentication
    $mail->Username = "myusername";  // SMTP username
    $mail->Password = "[email protected]"; // SMTP password

    $mail->From = "[email protected]";
    $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');
    $mail->addAttachment('files/file.xlsx');

    if(!$mail->Send())
    {
       echo "Message could not be sent. <p>";
       echo "Mailer Error: " . $mail->ErrorInfo;
       exit;
    }

    echo "Message has been sent";
}
880

Answer

Solution:

Just add some headers before sending mail:

<?php 
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com'; 
$to = '[email protected]'; 
$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: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

And one more thing. Themail() function is not working in localhost. Upload your code to a server and try.

122

Answer

Solution:

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('[email protected]', $subject, $message, $headers)

Use'' and not"".

This code works, but the email was received with half an hour lag.

619

Answer

Solution:

Mostly themail() function is disabled in shared hosting. A better option is to use SMTP. The best option would be Gmail or SendGrid.


SMTPconfig.php

<?php 
    $SmtpServer="smtp.*.*";
    $SmtpPort="2525"; //default
    $SmtpUser="***";
    $SmtpPass="***";
?>

SMTPmail.php

<?php
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;
        }
        else
        {
            $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");
            $talk["res"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpUser."\r\n");
            $talk["user"]=fgets($SMTPIN,1024);
            fputs($SMTPIN, $this->SmtpPass."\r\n");
            $talk["pass"]=fgets($SMTPIN,256);
            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");
            $talk["send"]=fgets($SMTPIN,256);
            //CLOSE CONNECTION AND EXIT ... 
            fputs ($SMTPIN, "QUIT\r\n"); 
            fclose($SMTPIN); 
            // 
        } 
        return $talk;
    } 
}
?>

contact_email.php

<?php 
include('SMTPconfig.php');
include('SMTPmail.php');
if($_SERVER["REQUEST_METHOD"] == "POST")
{
    $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();
}
?>
862

Answer

Solution:

If you only use themail()function, you need to complete the configuration file.

You need to open the mail expansion, and set theSMTP smtp_port and so on, and most important, your username and your password. Without that, mail cannot be sent. Also, you can use thePHPMail class to send.

331

Answer

Solution:

Try these two things separately and together:

  1. remove theif($_POST['submit']){}
  2. remove$from (just my gut)
49

Answer

Solution:

I think this should do the trick. I just added anif(isset and added concatenation to the variables in the body to separate PHP from HTML.

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: yoursite.com'; 
    $to = '[email protected]'; 
    $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>';
    } 
    else 
    { 
        echo '<p>Something went wrong, go back and try again!</p>'; 
    }
}

?>
979

Answer

Solution:

For anyone who finds this going forward, I would not recommend usingmail. There's some answers that touch on this, but not the why of it.

PHP'smail 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 frommail. 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 usemail to ultimately send the mail, but I would strongly recommend you not do that).

This means 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 callingisSMTP()), you can get a detailed transcript of the SMTP conversation using theSMTPDebug 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. Withmail 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).

278

Answer

Solution:

$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 class="page_speed_1833695416">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>";
}
8

Answer

Solution:

You can use config email by CodeIgniter. For example, using SMTP (simple way):

$config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'mail.domain.com', // Your SMTP host
        'smtp_port' => 26, // Default port for SMTP
        'smtp_user' => '[email protected]',
        'smtp_pass' => 'password',
        'mailtype' => 'html',
        'charset' => 'iso-8859-1',
        'wordwrap' => TRUE
);
$message = 'Your msg';
$this->load->library('email', $config);
$this->email->from('[email protected]', 'Title');
$this->email->to('[email protected]');
$this->email->subject('Header');
$this->email->message($message);

if($this->email->send()) 
{
   // Conditional true
}

It works for me!

384

Answer

Solution:

Try this

if ($_POST['submit']) {
    $success= mail($to, $subject, $body, $from);
    if($success)
    { 
        echo '
        <p>Your message has been sent!</p>
        ';
    } else { 
        echo '
        <p>Something went wrong, go back and try again!</p>
        '; 
    }
}
274

Answer

Solution:

Maybe the problem is the configuration of the mail server. To avoid this type of problems or you do not have to worry about the mail server problem, I recommend you use PHPMailer.

It is a plugin that has everything necessary to send mail, and the only thing you have to take into account is to have the SMTP port (Port: 25 and 465), enabled.

require_once 'PHPMailer/PHPMailer.php';
require_once '/servicios/PHPMailer/SMTP.php';
require_once '/servicios/PHPMailer/Exception.php';

$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
    //Server settings
    $mail->SMTPDebug = 0;
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = '[email protected]';
    $mail->Password = 'contrasenia';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;

    // Recipients
    $mail->setFrom('[email protected]', 'my name');
    $mail->addAddress('[email protected]');

    // Attachments
    $mail->addAttachment('optional file');         // Add files, is optional

    // Content
    $mail->isHTML(true);// Set email format to HTML
    $mail->Subject = utf8_decode("subject");
    $mail->Body    = utf8_decode("mail content");
    $mail->AltBody = '';
    $mail->send();
}
catch (Exception $e) {
    $error = $mail->ErrorInfo;
}
52

Answer

Solution:

First of all, you might have too many parameters for the mail() function... You are able to have of maximum of five,mail(to, subject, message, headers, parameters);

As far as the$from variable goes, that should automatically come from your webhost if your using the Linux cPanel. It automatically comes from your cPanel username and IP address.

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com';
$to = '[email protected]';
$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.

Themail($to, $subject, $message, etc.) in that order, or else there is a chance of it not working.

203

Answer

Solution:

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 www.AceITLab.com, 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.

436

Answer

Solution:

Make sure you have Sendmail installed in your server.

If you have checked your code and verified that there is nothing wrong there, go to /var/mail and check whether that folder is empty.

If it is empty, you will need to do a:

sudo apt-get install sendmail

if you are on an Ubuntu server.

580

Answer

Solution:

For those who do not want to use external mailers and want to mail() on a dedicated Linux server.

The way, how PHP mails, is described inphp.ini in section[mail function].

Parametersendmail-path describes how sendmail is called. The default value issendmail -t -i, so if you get a workingsendmail -t -i < message.txt in the Linux console - you will be done. You could also addmail.log to debug and be sure mail() is really called.

Different MTAs can implementsendmail. They just make a symbolic link to their binaries on that name. For example, in Debian the default is Postfix. Configure your MTA to send mail and test it from the console withsendmail -v -t -i < message.txt. Filemessage.txt should contain all headers of a message and a body, destination address for the envelope will be taken from theTo: header. Example:

From: [email protected]
To: [email protected]
Subject: Test mail via sendmail.

Text body.

I prefer to use ssmtp as MTA because it is simple and does not require running a daemon with opened ports. ssmtp fits only for sending mail from localhost. It also can send authenticated email via your account on a public mail service. Install ssmtp and edit configuration file/etc/ssmtp/ssmtp.conf. To be able also to receive local system mail to Unix accounts (alerts to root from cron jobs, for example) configure/etc/ssmtp/revaliases file.

Here is my configuration for my account on Yandex mail:

[email protected]
mailhub=smtp.yandex.ru:465
FromLineOverride=YES
UseTLS=YES
[email protected]
AuthPass=password
117

Answer

Solution:

Sendmail installation for Debian 10.0.0 ('Buster') was in fact trivial!

php.ini

[mail function]
sendmail_path=/usr/sbin/sendmail -t -i
; (Other directives are mostly windows)

Standard sendmail package install (allowing 'send'):

su -                                        # Install as user 'root'
dpkg --list                                 # Is install necessary?
apt-get install sendmail sendmail-cf m4     # Note multiple package selection
sendmailconfig                              # Respond all 'Y' for new install

Miscellaneous useful commands:

which sendmail                              # /usr/sbin/sendmail
which sendmailconfig                        # /usr/sbin/sendmailconfig
man sendmail                                # Documentation
systemctl restart sendmail                  # As and when required

Verification (of ability to send)

echo "Subject: sendmail test" | sendmail -v <yourEmail>@gmail.com

The above took about 5 minutes. Then I wasted 5 hours... Don't forget to check your spam folder!

183

Answer

Solution:

If you are running this code on a local server (i.e your computer for development purposes) it won't send the email to the recipient. It will create a.txt file in a folder namedmailoutput.

In the case if you are using a free hosing service, like000webhost orhostinger, those service providers disable themail() 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):

<?php
    $to      = '[email protected]';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: [email protected]' . "\r\n" .
        'Reply-To: [email protected]' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
?>
129

Answer

Solution:

You can use thePHPMailer and it works perfectly,here's a code example:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/phpmailer/phpmailer/src/Exception.php';
require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/phpmailer/src/SMTP.php';
$editor = $_POST["editor"];
$subject = $_POST["subject"];
$to = $_POST["to"];

try {

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->Mailer = "smtp";
        $mail->SMTPDebug  = 1;
        $mail->SMTPAuth   = TRUE;
        $mail->SMTPSecure = "tls";
        $mail->Port       = 587;
        $mail->Host       = "smtp.gmail.com";//using smtp server
        $mail->Username   = "[email protected]";//the email which will send the email 
        $mail->Password   = "XXXXXXXXXX";//the password

        $mail->IsHTML(true);
        $mail->AddAddress($to, "recipient-name");
        $mail->SetFrom("[email protected]", "from-name");
        $mail->AddReplyTo("[email protected]", "reply-to-name");
        $mail->Subject = $subject;
        $mail->MsgHTML($editor);




        if (!$mail->Send()) {
            echo "Error while sending Email.";
            var_dump($mail);
        } else {
            echo "Email sent successfully";
        }
    }
} catch (Exception $e) {
    echo $e->getMessage();
}
995

Answer

Solution:

You can see your errors by:

error_reporting(E_ALL);

And my sample code is:

<?php
    use PHPMailer\PHPMailer\PHPMailer;
    require 'PHPMailer.php';
    require 'SMTP.php';
    require 'Exception.php';

    $name = $_POST['name'];
    $mailid = $_POST['mail'];
    $mail = new PHPMailer;
    $mail->IsSMTP();
    $mail->SMTPDebug = 0;                   // Se