问题描述:

Why the below code not sending mail to me? What is the error?

<?php

if(isset($_POST['name'])){

$msg="Name: ".$_POST['name']."\n Email: ".$_POST['email']."\n Address: ".$_POST['city']."\n Phone: ".$_POST['phone'];

mail('[email protected]', 'New Trial Request', $msg);

echo '<h2 align="center" style="color:green">Thank you for your message.</h2>';

} ?>

No error I got. Just I have not received my email at inbox. This is running on IIS Server.

网友答案:

Try this

$headers = 'From: [email protected]' . "\r\n";
$validate = mail('[email protected]', 'New Trial Request', $msg, $headers);

if($validate)
{
  echo '<h2 align="center" style="color:green">Thank you for your message.</h2>';
}
else
{
  echo '<h2 align="center" style="color:red">Something went wrong.</h2>';
}

If you get 'Something went wrong' it means problem is in your mail server and not in PHP code.

网友答案:

I suggest you to use PEAR::Mail package. You can send emails via SMTP then.

require_once "Mail.php";

$from = "[email protected]";
$to = "[email protected]";
$subject = "New Trial Request";
$body = "Name $name, Address $address ...";
$host = "ssl://smtp.gmail.com";
$port = 465;
$username = "[email protected]";
$password = "password";

$headers = array(
    'From' => $from,
    'To' => $to,
    'Subject' => $subject
);
$smtp = Mail::factory(
    'smtp',
    array(
        'host' => $host,
        'port' => $port,
        'auth' => true,
        'username' => $username,
        'password' => $password
    )
);

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
    echo("<p>" . $mail->getMessage() . "</p>");
} else {
    echo("<p>Message has been sent!</p>");
}
网友答案:

You might have to send Mail Using SMTP Authenticationas which is required by many mail servers. Check this link for further details.

网友答案:

May be your php configuration is not complete, see in C://xampp/php/php.ini in:

sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"

This is for activate email. May be your setting is:

;sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"
网友答案:

Although I didnt change anything in your code. please try this

<?php
if(isset($_POST['name'])){

    $to = '[email protected]';
    $subject = 'the subject';
    $message = 'hello';

    $msg='Name:'.$_POST{name}. "\r\n".
         'Email: '.$_POST{email}. "\r\n".
        'Address: '.$_POST{city}. "\r\n".
         'Phone: '.$_POST{phone}. "\r\n";

    $headers = 'From: [email protected]' . "\r\n" .
    'Reply-To: [email protected]' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

    $sent = mail($to, $subject, $message, $headers);
    var_dump($sent) // just to debug
    echo '<h2 align="center" style="color:green">Thank you for your message.</h2>';

} ?>
相关阅读:
Top