send email in background process in php

7.1k Views Asked by At

I want to send a welcome email when a user registers in my app. When a user registers he gets redirected to his profile page. I tried sending email while user creation but the email() takes 7 seconds to send email, and the page waits till then and then redirects the user to profile after 7 sec.

This is not desired. I want to redirect user as soon he registers, and send an email along the process. It takes 7 sec don't know why. i tried it online on godaddy and hostgator account as well as on my localhost.

BTW: i am using PHPMailer to send email.

How can can i make a standalone process which on invoke calls my sendMail.php with email $_POST[] parameters {to, subject, body}.

i though ajax call will do the trick, but as soon as my page redirects from registration to profile, the email script stops. I tried this code:

<script language="JavaScript">
    $.post( "sendMail.php", { to: "$to", subject: "$subject", htmlBody: "$htmlBody", altBody: "$altBody" } );
location.href=profile.html
</script>

Please help, i searched a lot but they work on shell which i am not, and other solutions were unix/linux based. i want to make it work on xampp as well as godaddy linux shared hosting, with NO ssh access.

3

There are 3 best solutions below

2
On BEST ANSWER

You could use Mail_Queue, which is a job queue specifically for sending emails, or utilise Zend_Queue [ZF1, ZF2] to write something customised to work with PHPMailer. You might even consider using Gearman.

2
On

You could try to put the javascript in your profile page so it runs once they hit the profile page and not on the form submit. Just need to check if the welcome email has been sent already in you sendMail.php script.

But using this script to send an email may not a very good idea as it could enable a malicious user to send an email with what ever content they wanted to whoever they wanted and if it was marked as spam then it would be your server that got blocked. It is a very common technique used by "spammers".

You would have to be very careful in how you handeled the email before it was sent so as not to breach your agreement with your hosting company.

3
On

Php is single threading language. This means that you can not start a job before previus one executed (and finished)...

You may change task order. I mean you may send the email, after welcome page completely rendered.

Try with this order;

1) register user

2) show welcome page,

3) send welcome email....

with this order, your new user will not wait for 7 seconds before see welcome page.