无法使用 php 中的邮件功能发送电子邮件


Unable to send email using mail function in php

我的公司把一个由别人开发的现有项目交给了我。我必须解决其中的一些问题,但在其中一个问题中我卡住了。电子邮件不是从网站发送的。我不确定为什么会发生这种情况。该代码只是发送电子邮件的简单php电子邮件功能。但它仍然不起作用有人能猜到我错过了什么吗?

$to = "test@gmail.com";
$subject = "Property Posted";
$message="TestMessage"
$headers = "MIME-Version: 1.0" . "'r'n";
$headers .= "Content-type:text/html;charset=UTF-8" . "'r'n";
$form="www.xxxxxxxxxxxxxxxxxxxxx.com";
// More headers    
$headers .= 'From: <xyz@example.com>' . "'r'n";
$headers .= 'Cc: myboss@example.com' . "'r'n";
$checkmail = mail($to,$subject,$message,$headers,$form);
if($checkmail) {
    echo "email sent";
} else {
    echo failed"
}

它总是击中else,虽然我不知道为什么。

你没有定义$to$subject。请检查以下代码:

 <?php
    $to      = 'nobody@example.com';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: webmaster@example.com' . "'r'n" .
               'Reply-To: webmaster@example.com' . "'r'n" .
               'X-Mailer: PHP/' . phpversion();
    mail($to, $subject, $message, $headers);
  ?>

通过在命令行上执行以下命令来测试服务器邮件服务。

echo "message" | mail -s subject youremail@gmail.com

然后尝试以下代码。

error_reporting(E_ALL);
ini_set('display_errors',1);
$to = "test@gmail.com";
$subject = "Property Posted";
$message="TestMessage";
$headers = "From: webmaster@example.com" . "'r'n" .
"CC: somebodyelse@example.com";
mail($to,$subject,$message,$headers);

有时电子邮件会变成垃圾邮件,所以另一种可能性是通过梨安装邮件和net_smtp。

pear install Mail
pear install Net_Smtp

然后,您可以使用SMTP身份验证将邮件发送到另一台服务器:

require_once "Mail.php";
$body = "messages in body part'n";
$subject = "Subject of email message";
$mail_to = "abc@gmail.com";
$mail_from = "efg@gmail.com";
//SMTP Configuration
$host = "smtp.server.com""; // Or IP address";
$username = "username";
$password = "password";
$smtp = Mail::factory('smtp',
 array (
 'host' => $host,
 'auth' => true,
 'username' => $username,
 'password' => $password
));
$headers = array (
 'From' => $mail_from,
 'To' => $mail_to,
 'Subject' => $subject
);
$mail = $smtp->send($mail_to, $headers, $body);
if (PEAR::isError($mail)) {
 echo "Cound not seend the message";
}

使用 PHP 的 mail() 函数是可能的。请记住,邮件功能在本地服务器中不起作用

<?php
 $to      = 'nobody@example.com';
 $subject = 'the subject';
 $message = 'hello';
 $headers = 'From: abc@example.com' . "'r'n" .
       'Reply-To: abc@example.com' . "'r'n" .
       'X-Mailer: PHP/' . phpversion();
 mail($to, $subject, $message, $headers);
 ?>