PHP:从外部脚本发送电子邮件

时间:2012-08-16 17:52:21

标签: php email

朋友们,这看起来应该很容易,但我画的是空白。我想给人们发一个链接。他们应该输入他们的电子邮件地址,点击“提交”,然后将电子邮件显示在他们的收件箱中。 PHP必须是外部文件。所以在我的页面上我有......

<form action="http://www.myotherdomain.com/email.php" method="post">Email: 
    <input type="text" name="email" />
    <input type="submit" />
</form>

在我的php文件中,我有......

<?php
    $to = $_POST["email"];
    $subject = "Test mail";
    $message = "Hello! This is a simple email message.";
    $from = "address@someisp.com";
    $headers = "From:" . $from;
    mail($to,$subject,$message,$headers);
?> 

它工作正常并发送电子邮件但是我点击提交按钮后将它带到email.php页面。我不想离开我正在访问的页面。我只是想按下按钮并发送电子邮件而不让我离开页面。奖金将是电子邮件发送时出现的消息。

谢谢!

4 个答案:

答案 0 :(得分:0)

如果您想在没有页面加载的情况下执行此操作,则需要使用AJAX。如果您对表单提交导致页面加载没问题,那么您有两个选择。将电子邮件逻辑放入当前页面并将页面重新发布到自身,或者执行从mail.php脚本重定向回用户来自的页面。

答案 1 :(得分:0)

您可以添加目标和iframe:

<form action="http://www.myotherdomain.com/email.php" target="aframe" method="post">Email: 
    <input type="text" name="email" />
    <input type="submit" />
</form>

<iframe src="about:blank" style="display:none" name="aframe" id="aframe"></iframe>

不需要ajax,这也适用于没有javascript的用户,但是有消息&#34;发送的电子邮件&#34;或者这样会有所帮助。您可以通过email.php回显警报:

echo "<script type='text/javascript'>alert(\"Email sent\");</script>";

如何做到这一点的真实简单示例。

答案 2 :(得分:0)

你有2个选项要么使用AJAX(jQuery会是一个快速的解决方案)

$('form').submit(function(){
    $.ajax({
        type: 'POST',
        url: 'http://www.myotherdomain.com/email.php',
        data: $(this).serialize(),
        success: function(data) {
            alert('Message sent!');
        }
    });
    return false;
});

或在邮件完成后进行重定向:

header('Location: http://www.yourdomain.com');
exit;

答案 3 :(得分:0)

您需要使用Jquery / Ajax执行此操作。这是一个简单的脚本,可以使用当前页面调用email.php:

<script src="http://code.jquery.com/jquery-1.7.min.js"></script>

在体内:

<script type="text/javascript" >
function process(email){
$.post("email.php",{email:email},function(result){
alert(result); 
});

};
</script>

<img src="whatever.png" onClick="process('their_email@example.com');">
相关问题