1

I have this simple program, which displays 'Success' in sending mail. But it is not actually received in the inbox or spam. What could be the issue?

mail.php

<?php

$to = "xyz@gmail.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: abc@gmail.com";

$result = mail($to,$subject,$txt,$headers);

if(!$result) {
     echo "Error";
} else {
    echo "Success";
}

?>
Community
  • 1
  • 1
Delegate
  • 45
  • 10
  • 1
    What does your mail server's (MTA) log say? Also keep in mind that `mail` does not return the result of the message actually being delivered to the recipient. http://php.net/manual/en/function.mail.php – Will B. Nov 21 '17 at 04:25
  • You aren't allowed to send emails from a gmail address unless you authenticate with google first. These emails will simply be blocked. Have a read through the docs for phpMailer @ https://github.com/PHPMailer/PHPMailer – Erik Nov 21 '17 at 04:32
  • So what can I do to actually send an email? – Delegate Nov 21 '17 at 04:35

1 Answers1

1

As mentioned in my comment, can't send unauthorized emails from / to a gmail address. Have a look at PHPMailer => https://github.com/PHPMailer/PHPMailer Download the zip file https://github.com/PHPMailer/PHPMailer/archive/master.zip and upload to your server.

And use the following as an example, change things where needed:

<?php
require_once('/path/to/PHPMailerAutoload.php');

$mail = new PHPMailer;

$mail->isSMTP();
$mail->SMTPDebug = false;
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;

$mail->Username = 'from@gmail.com';
$mail->Password = 'password';
$mail->setFrom('from@gmail.com', 'From Name (freeform string)');
$mail->addAddress('to@gmail.com'); //call this multiple times for multiple recipients
$mail->Subject = 'Subject';
$mail->msgHTML('<h3>Hello World</h3>');
$mail->AltBody = 'alternative body if html fails to load';
//$mail->addAttachment('/path/to/file/); //OPTIONAL attachment

if (!$mail->send()) {
    echo "Mailer Error: ";
    echo $mail->ErrorInfo;
} else {
    echo "Email sent";
}
?>
Erik
  • 118
  • 6
  • Thanks. But is there any other way instead of using 3rd-party library? – Delegate Nov 21 '17 at 04:43
  • You could also use the pear mail functionality. check phpinfo() if you have pear installed and check out this question/answer: https://stackoverflow.com/questions/712392/send-email-using-the-gmail-smtp-server-from-a-php-page – Erik Nov 21 '17 at 04:45
  • Or read through this: https://stackoverflow.com/questions/24644436/php-mail-function-doesnt-complete-sending-of-e-mail So many answers with a simple google search – Erik Nov 21 '17 at 04:47
  • thanks, I will go through this – Delegate Nov 21 '17 at 04:52
  • 1
    Erik, your closure flag was sufficient. No need to post an answer. – mickmackusa Nov 21 '17 at 05:52