Rama Lingam Rama Lingam - 1 year ago 108
PHP Question

PHP mail() function is not working in namecheap server

I am new in namecheap domain server.
I am trying to send a simple mail on that namecheap server. It wasn't sending mail and returned an empty value not any error.

Here is my sample code.

$to = "raamanmca@gmail.com";
$subject = "HTML email";
$message = "Hello this is testing mail";

// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// More headers
$headers .= 'From: <ramalingam@binaryswan.com>' . "\r\n";
$headers .= 'Cc: myboss@example.com' . "\r\n";

echo "Mail sent...";
echo "Mail not sent";

Suppose i assign $to and $from mailID within a namecheap server mail's then mail sent successfully.



But i am changing the mail $to OR $from into gmail server like
then it will not send a mail and is also returning empty value without error. How to fix.

From (Not receiving email from the PHP mail() method)
Only domains that are hosted on our servers can be used in 'From' field. Any domain that is not hosted with us cannot be added to 'From' field. We had to take this measure to prevent sending spam using forums, guest books and contact forms scripts. For your site scripts to work properly you should set 'From' field to email account that has been created in your cPanel.

It's related to my issue but i don't know how to "set 'From' field to email account in my cPanel."

Answer Source

Darren is right. I am changing the PHP mail() function to PHPMailer mail() method.Download link - https://github.com/PHPMailer/PHPMailer Now the mail was sent successfully. Thanks to Comments. Here is answer code :

require 'class.phpmailer.php';

$mail = new PHPMailer;

$mail->Host = 'smtp1.example.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'user@example.com';                 // SMTP username
$mail->Password = 'secret';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;                                    // TCP port to connect to

$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('ramalingam.p@pickzy.com', 'Rama Lingam');     // Add a recipient
$mail->addAddress('raamanmca@gmail.com');               // Name is optional
$mail->addReplyTo('info@example.com', 'Information');


$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo '<br>Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';