在PHP的帮助下从JS代码发送电子邮件

时间:2014-02-16 16:02:58

标签: javascript php html email

我希望在PHP的帮助下从JS代码发送一封电子邮件。

function validateForm(){


    // sending a mail 
    $.get("../sendMail.php");


    // more code

}

我有一个名为sendMail.php的文件,它存储在服务器上:

sendMail.php:

<?php
session_start();  
if(($_POST['name'] == '') || ($_POST['phone'] == '') || ($_POST['email'] == '')) {
/*------
echo 'Complete the forms correctly <br>
Click <a href="contact.php">here</a> to return on contact us page.'; 
-------*/
header("location:index.php");
} else {

$to = 'johnny@gmail.com';  
$send_date = date('d-m-Y H:i:s');
$subject = 'Hello';

if (isset($_POST['check'])) {
    $check = "yes";
} else {
    $check = "no";
}

$message .= "<br>"."<br>";
$message .= "<strong>Date and time:</strong> ".$send_date ."<br/>";
$message .="<strong>Name:</strong> ".$_POST['name']."<br/>";
$message .="<strong>Phone: </strong> ".$_POST['phone']."<br/>";
$message .="<strong>Email: </strong> ".$_POST['email']."<br/>";
$message .="<strong>Agree to post ads:</strong> ".$check."<br/>";

$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8"' . "\r\n";
$headers .= 'From: someone@somewhere.com' . "\r\n";

mail($to, $subject, $message,$headers);


/*-----
echo 'The message was send <br>
Click <a href="index.php">here</a> to return on home page.';
window.location.href=""
-----*/
$_SESSION['thankyou']='Your email has been sent successfully';
header ('Location: index.php');
}

?>

但是当我运行JS代码时,不会发送电子邮件。

  1. 有没有办法发送邮件,而不使用客户端的某种电子邮件客户端?

  2. 如何修复此代码?感谢

2 个答案:

答案 0 :(得分:0)

您正在向PHP处理程序发出HTTP GET请求,而PHP处理程序要求使用HTTP POST和适当的POST变量执行它。尝试使用正确的变量POST到URL。

(另外,您应该添加一个特殊的唯一签名,以防止该表单被用于垃圾邮件)。

答案 1 :(得分:0)

尝试使用此

$.post( "../sendMail.php", { name: "John", phone: "1234", email:"abc@test.com" } );