php – PHPMail method not working in ubuntu with LAMPP-ThrowExceptions

Exception or error:

I created a contact form and it works correctly with phpmail method, but I’m facing one issue with not sent email. I’m getting one error based on below code using Ubuntu and LAMPP

if (isset($_POST['sendmail'])){
     $person_name=$_POST['c_name']; 
     $email=$_POST['c_email'];
     $subject=$_POST['c_subject'];
     $message=$_POST['c_message'];

    $toEmail = "ourgmail@gmail.com";
    $mailHeaders = "From: " . $person_name . "<". $email .">\r\n";
    if(mail($toEmail,$subject,$message,$mailHeaders)) {  // checking sent or not
       echo "<script>alert('success')</script>";
    } else {
        echo "<script>alert('error')</script>"; //  email not sent and getting error here
    }
}
How to solve:

According to this comment at PHP mail() documentation:

Often it’s helpful to find the exact error message that is triggered
by the mail() function. While the function doesn’t provide an error
directly, you can use error_get_last() when mail() returns false.

<?php $success = mail('example@example.com', 'My Subject', $message); 
if (!$success) {
    $errorMessage = error_get_last()['message']; 
} ?>

Also, keep in mind that to mail() work, your system must be properly configured to send emails. Since setting up a mail server is not so simple (there’s a lot of anti-spam restrictions), if you want to test it out, you can setup a SSMTP service on your system that uses a third party SMTP service like http://mailgun.com to sent it. Check this question on Unix&Linux.

Leave a Reply

Your email address will not be published. Required fields are marked *