I have PHP's mail()
using ssmtp which doesn't have a queue/spool, and is synchronous with AWS SES.
I heard I could use SwiftMail to provide a spool, but I couldn't work out a simple recipe to use it like I do currently with mail()
.
I want the least amount of code to provide asynchronous mail. I don't care if the email fails to send, but it would be nice to have a log.
Any simple tips or tricks? Short of running a full blown mail server? I was thinking a sendmail
wrapper might be the answer but I couldn't work out nohup
.
Your best bet is with a stacking or spooling pattern. It's fairly simple and can be described in 2 steps.
You have a lot of ways to do this, but handling thread is not necessarily the right choice.
from
,to
,message
,sent
(boolean set totrue
when you have sent the email).Example with register_shutdown_function
I'm using asynchronous php execution by using beanstalkd.
It is a simple message queue, really lightweight and easy to integrate.
Using the following php wrapper for php https://github.com/pda/pheanstalk you can do something as follows to implement a email worker:
Then the job would be done in a code placed into a separate php file.
Something like:
You can run separately this php file, as an independent php process. Let's say you save it as sender.php, it would be run in Unix as:
php /path/to/sender/sender.php & && disown
This command would run the file and alsow allow you to close the console or logout current user without stopping the process.
Make sure also that your web server uses the same php.ini file as your php command line interpreter. (Might be solved using a link to you favorite php.ini)
I hope it helps.
Pthreads is your friend :)
This is a sample of how i made in my production application
TEST SCRIPT EXAMPLE
Let me know if you need further help for installing and using thread in PHP
For logging system, i strongly advice you to use Log4PHP : powerful and easy to use and to configure
For sending mails, i also strongly advice you to use PHPMailer
An easy way to do it is to call the code which handles your mails asynchronously.
For example if you have a file called email.php with the following code:
You can then call this asynchronously in a normal request like
And the request will finish without waiting for email.php to finish sending the e-mails. Logging could be added as well in the file that does the e-mails.
Variables can be passed into the exec between the called filename and
> /dev/null
likeMake sure these variables are safe with escapeshellarg(). In the called file these variables can be used with $argv
php-fpm
You must run php-fpm for fastcgi_finish_request to be available.
It's pretty easy queuing up any arbitrary code to processed after finishing the request to the user:
Hipster background worker
Instantly time-out a curl and let the new request deal with it. I was doing this on shared hosts before it was cool. (it's never cool)