PHP使用邮件功能发送电子邮件

时间:2015-12-02 06:15:08

标签: php

我正在尝试使用发送电子邮件但无法执行此操作,而我正在将数据导入MySQL数据库。

我已经发布了我的全部代码,请检查并告诉我哪里出错了。

$objConnect = mysql_connect("localhost","username","pwd");
$objDB = mysql_select_db("database");

$strName = $_POST["name"];
$strEmail = $_POST["email"];

$to      = $strEmail;
$subject = 'the subject';
$message = 'hello';
$headers = 'From: mymail@gmail.com' . "\r\n" .
'Reply-To: mymail@gmail.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

$strSQL = "insert into data (name, email) VALUES ('".$strName."','".$strEmail."')";
$objQuery = mysql_query($strSQL);

if(!$objQuery)
    {
        $arr['StatusID'] = "0"; 
        $arr['Message'] = "Cannot save data!";  
    }
    else
    {
        mail($to, $subject, $message, $headers);
        $arr['StatusID'] = "1"; 
        $arr['Message'] = "Data saved successfully";    
    }

    mysql_close($objConnect);

    echo json_encode($arr);

2 个答案:

答案 0 :(得分:0)

此代码确实有用......

<?php
    $to      = 'to_email@gmail.com';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: mymail@gmail.com' . "\r\n" .
    'Reply-To: mymail@gmail.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
    $errLevel = error_reporting(E_ALL ^ E_NOTICE);  // suppress NOTICEs
    if(!mail($to, $subject, $message, $headers)){
        error_reporting($errLevel);
    }
?>

答案 1 :(得分:0)

您尚未在代码中添加mail()功能,那么它将如何发送邮件以及从localhost发送电子邮件,它应该正确配置。下面的代码可以在服务器上运行。

$objConnect = mysql_connect("localhost","username","pwd");
$objDB = mysql_select_db("database");
$strName = $_POST["name"];
$strEmail = $_POST["email"];
$to      = $strEmail;
$subject = 'the subject';
$message = 'hello';
$headers = 'From: mymail@gmail.com' . "\r\n" .
           'Reply-To: mymail@gmail.com' . "\r\n" .
           'X-Mailer: PHP/' . phpversion();
if(!mail($to, $subject, $message, $headers)){
  echo 'Mail cant be send';
}
else
{
$strSQL = "insert into data (name, email) VALUES ('".$strName."','".$strEmail."')";
$objQuery = mysql_query($strSQL);
if(!$objQuery)
   {
    $arr['StatusID'] = "0"; 
    $arr['Message'] = "Cannot save data!";  
}
else
{
    mail($to, $subject, $message, $headers);
    $arr['StatusID'] = "1"; 
    $arr['Message'] = "Data saved successfully";    
}
echo json_encode($arr);
  }
   mysql_close($objConnect);