I know how to send email using PHPmail. But what if I need to send lots of emails?
This could be a "notification" to site subscribers when a new message is posted. Doing that directly in page handler will seriously affect performance and make browser loading too slow. So I need to have this job done in the "background".
How can I "schedule" something in PHP, in my case - sending emails? In C++ for example I would create a separate thread but AFAIK there is no such thing as multithreading in PHP.
Create CRON job that sends out email-queue you've saved in a database:
Save an email with all info into a db.
Use a CRON job to periodically (like every half hour or so - depends on your hosting provider and the number of emails you're sending out) grab emails from the queue and send them out. Then set a sent
flag on the email in the database, add sending info you want (e.g. time, errors, header, ...).
Be sure to break up the emails to chunks and send out them with pauses to avoid problems with anti-spam and anti-flood protections of some email servers. Some mailer libraries have plugins for this (like SwiftMailer).
To schedule such things it is best to use cronjobs, this is defined on the server itself in stead of in PHP. The cronjob can, however, call a PHP script to be executed.
Doing this with a cronjob has some advantages because it will not (directly) affect end-user performance and you can make it run at certain times.
Have all your email data stored in a Mysql database. Table structure could be like.
TO_EMAIL_ID | EMAIL_TYPE | EMAIL SUBJECT | EMAIL_CONTENT | PROCESSED | INSERT_TIME .
insert all your email content into this table. And have a php script which fetches data from this table and sends email in batches, and deletes/Marks as processed the emails that are sent. lets say that file is sendMailers.php Then you can set a cron job to run this file every 5 minutes. see http://www.foogazi.com/2006/12/07/understand-cron-jobs-in-5-minutes/
*/5 * * * * PATH_TO_PHP sendMailers.php
You can use a cron job to run a script periodically and send out any outstanding notifications.
An alternative would be to start another process in the background, using something like: exec('php send_notifications.php 1>/dev/null 2>1 &');
(notice the stuff at the end).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With