Reputation: 20245
in php5 web app, getting email address from user and sticking it into database, but want to send the email without user waiting for the email to complete. using gmail, sometimes takes a few seconds.
thinking about fopen( "http://self.com/mailer.php", "r" )
, where mailer.php
would do the actual mailing. will this work?
Upvotes: 1
Views: 286
Reputation: 4726
There are two approaches that have worked well for me in the past.
Database Email Queue
Create an "email_queue" table in your database or whatever else you are using for persistent storage. Each entry contains everything you will need in order to send an email (e.g. Subject, recipient, sender, body, etc...) and a "sent" flag field. To send an email you add an entry to this table using a helper class.
Then you create a cli php script that reads from the queue table filtering for entries that have the sent flag set to 0, send the email and finally set the sent flag to 1. This script needs to run in a cron job, but since you probably want to run it more often than one minute, you can use something like Frequent-cron. The scheduled task should only run in one web server in case you have many (and assuming your persistent storage is shared).
Local email queue
I've also had some success configuring a local postfix server on each web server to deliver mail using an external smtp service. The goal here is to get postfix to accept the email as fast as possible (because it is local) and then deliver it via the external SMTP server in a different process. Postfix will act as an intermediary queue.
I personally like the first solution because it gives your app more information about email delivery for statistical analysis' record keeping, etc..
Hope that helps.
Upvotes: 1