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

Friends, this seems like it should be easy but I'm drawing a blank. I want to email people a link. They should enter their email address, hit "submit", and have the email show up in their inbox. The PHP has to be an external file. So on my page I have...

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

On my php file I have...

<?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);
?> 

It works fine and sends the email BUT it takes me to the email.php page after I hit the submit button. I don't want to leave the page I'm on. I just want to hit the button and have the email sent without me leaving the page. A bonus would be a message that that presents when the email has been sent.

Thank you!

If you want to do it without a page load, you will need to use AJAX. If you are OK with the form submit causing a page load, then you have two options. Either put the email logic into the current page and post the page back onto itself, or perform a redirect from the mail.php script back to the page the user was coming from.

You can add target and an 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>

No need for ajax, this will also work for users without javascript, but a message "email sent" or so would be helpfull. You can just echo an alert from email.php:

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

Real simple example of how you could do this.

you have 2 options either use AJAX (jQuery would be a quick solution)

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

or do a redirect after the mail finishes:

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

You'll need to do this with Jquery/Ajax. Here is a simple script that should work with your current page calling email.php:

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

in the body:

<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');">