manlikeangus
manlikeangus

Reputation: 421

Send Automated E-Mails Based on MySQL Dates

I want to be able to send emails automatically based on mysql dates. I know I can schedule them using Crontabs, but the problem is that Crontabs only specifies days, months, weeks etc. - it isn't specific enough..

The MySQL table is filled with different dates. I want it so that I can automatically send emails when it is say, 3 months from the date on a particular record.

Does anyone know what I can do?

Upvotes: 0

Views: 2568

Answers (1)

Cody Caughlan
Cody Caughlan

Reputation: 32748

Schedule a cron that runs once a day that checks for records that need an email to be sent that day.

Imagine you had a column like notify_at which is a datetime - then every day your cron basically does

SELECT * FROM records WHERE notify_at = DATE(NOW())

Your cron can be stored in /etc/cron.d

/etc/cron.d/send_reminders:

# run once a day at 1AM
0 1 * * * someuser /path/to/your/script

Where the contents of the script is your logic, in psuedo-code:

results = fetch_by_sql("SELECT * FROM records WHERE notify_at = DATE(NOW()) AND last_notified_at IS NULL");
foreach(results as record) {
  send_email(record.recipient, "Your subject", "Your body");
  /* mark the record as notified so we dont ever send multiple emails */
  update_sql("UPDATE records SET last_notified_at = NOW() WHERE id = " + record.id);
}

Upvotes: 2

Related Questions