为什么mail()不发送电子邮件?

时间:2012-07-31 05:25:12

标签: php

为什么以下代码不向我发送邮件?错误是什么?

<?php
if(isset($_POST['name'])){
    $msg="Name: ".$_POST['name']."\n Email: ".$_POST['email']."\n Address: ".$_POST['city']."\n Phone: ".$_POST['phone'];
    mail('sganake@gmail.com', 'New Trial Request', $msg);
    echo '<h2 align="center" style="color:green">Thank you for your message.</h2>';

} ?>

我没有错误。我刚收到收件箱中的电子邮件。这是在IIS服务器上运行。

5 个答案:

答案 0 :(得分:0)

试试这个

$headers = 'From: from@address.com' . "\r\n";
$validate = mail('sganake@gmail.com', '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>';
}

如果获得'Something went wrong',则表示问题出现在您的邮件服务器中而不是PHP代码中。

答案 1 :(得分:0)

您可能必须使用许多邮件服务器所需的SMTP身份验证发送邮件。 查看this link了解更多详情。

答案 2 :(得分:0)

可能是您的php配置不完整,请参阅C://xampp/php/php.ini in:

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

这是用于激活电子邮件。可能是你的设置是:

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

答案 3 :(得分:0)

我建议你使用PEAR::Mail包。您可以通过SMTP发送电子邮件。

require_once "Mail.php";

$from = "your@gmail.com";
$to = "sganake@gmail.com";
$subject = "New Trial Request";
$body = "Name $name, Address $address ...";
$host = "ssl://smtp.gmail.com";
$port = 465;
$username = "your@gmail.com";
$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>");
}

答案 4 :(得分:-1)

虽然我没有更改代码中的任何内容。请试试这个

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

    $to = 'sganake@gmail.com';
    $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: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\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>';

} ?>