Sending an email using SwiftMailer (PHP) every X minutes

Tags: ,



I can make my code work via sending emails whenever a client enters a specific page, the problem is that if the user/client reloads the page, a new email is sent, and that can lead to hundreds of mails being sent from my smtp server.

I am searching for a simple alternative which can only send a verification email every 5/10/15 minutes. Not when the user reloads the page.

Should I use javascript or a simple sleep on the function would work.

PD: Emails are being sent via $_SESSION variables on php.

Answer

You could either use a cron job for this (if your hosting environment allows you to define one), or keep track of when you’ve last send your emails yourself.

In the latter case, you could for example do:

/**
 * Get the current date & time.
 *
 * @return String
 */
function now() {

  return date('Y-m-d H:i:s'); 
}

/**
 * Store last send date. For the sake of simplicity, let's
 * write it to a file. 
 *
 * @return String
 */
function last_send_update($date) {

  file_put_contents('mails_last_send.json', json_encode(['date' => $date]));
}

/**
 * Get last send date from a file. 
 *
 * @return String
 */
function last_send_get() {

  if (!file_exists('mails_last_send.json')) {

    last_send_update(now());
  }

  return json_decode(file_get_contents('mails_last_send.json'))->date;
}

/**
 * Mock sending mails.
 */
function send_mails() {}

// Do the actual math & decide what to do.
  
$last_send = date_create(last_send_get());
$now       = date_create(now());
$diff      = date_diff($now, $last_send)->i; // Difference in minutes

if ($diff >= 10) { 
  
  send_mails();
  last_send_update($now);
}

For Cron & how to use it, see:



Source: stackoverflow