Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to schedule email notifications in php

Tags:

php

email

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.

like image 353
Captain Comic Avatar asked Mar 09 '11 09:03

Captain Comic


4 Answers

Create CRON job that sends out email-queue you've saved in a database:

  1. Save an email with all info into a db.

  2. 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).

like image 54
Czechnology Avatar answered Nov 01 '22 14:11

Czechnology


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.

like image 31
gnur Avatar answered Nov 01 '22 13:11

gnur


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
like image 2
DhruvPathak Avatar answered Nov 01 '22 14:11

DhruvPathak


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).

like image 2
Daniel Dinu Avatar answered Nov 01 '22 13:11

Daniel Dinu