问题
In my web application, when a user makes a change to their account, I call the php mail() function to send that user an email notification. After implementing this, I found that the account change action takes a very large amount of time (>20 seconds) to complete. I suspect that this is because PHP waits for the mail() function to send the email. Is there any way to make this call without waiting and immediately continue to the next line of code?
Thanks,
Paul
回答1:
Create another PHP script (we'll call it "mailuser.php" for this example). In this file your code would look for activated accounts that haven't been emailed yet... then send the email.
In your original code (after activating the account) call :
exec("php mailuser.php > /dev/null 2>&1 &");
This should spawn the process, but not wait for it to return.
For more information, see these posts : php exec command (or similar) to not wait for result & Run PHP Task Asynchronously
You could also elect to pass the user id on the command line, so that the mailuser.php doesn't have to look for the users based on a field/flag.
回答2:
You could put the call to the mail function in a separate php file called, says, sendMail.php, and then send the request to the function with (jQuery AJAX)[https://api.jquery.com/jQuery.ajax/].
$.ajax({
type: "POST",
url: "sendMail.php",
data: { name: "Foo", email: "foobar@baz.com" }
})
.done(function( msg ) {
alert( "Email sent: " + msg );
});
回答3:
You can send Ajax call for sending mail and then for security purposes if the mail is not sent you can call a rollback on database query, this way your code will be secure.
回答4:
I had the same issue. Write a sendmail.php program and call it with ajax.
<?
session_start();
header("Content-Type: text/html; charset=iso-8859-1");
require_once("libreria/class.phpmailer.php");
$mail = new PHPMailer();
$body="";
$body.="<body>";
$body.=$_POST['cbody'];
$body.="</body>";
$mail->IsSMTP();
$mail->SMTPAuth = true;
//$mail->SMTPDebug = 2;
$mail->Host = "mail.xxx.xxx";
$mail->Port = 25;
$mail->Username = "usermail@xxx.xxx";
$mail->Password = "xxxxxx";
$mail->From = "usermail@xxx.xxx";
$mail->FromName = "xxx";
$mail->Subject = $_POST['subject'];
$mail->WordWrap = 50;
$mail->MsgHTML($body);
$mail->AddAddress($_POST['email'], "User");
$mail->IsHTML(true);
$mail->Send();
?>
(You can use the response of the ajax call to manage errors).
来源:https://stackoverflow.com/questions/21941209/prevent-php-from-waiting-for-mail-function