简体   繁体   English

每 X 分钟使用 SwiftMailer (PHP) 发送 email

[英]Sending an email using SwiftMailer (PHP) every X minutes

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.每当客户端进入特定页面时,我都可以通过发送电子邮件来使我的代码工作,问题是如果用户/客户端重新加载页面,则会发送新的 email,这可能导致从我的 smtp 服务器发送数百封邮件.

I am searching for a simple alternative which can only send a verification email every 5/10/15 minutes.我正在寻找一个简单的替代方案,它只能每 5/10/15 分钟发送一次验证 email。 Not when the user reloads the page.不是当用户重新加载页面时。

Should I use javascript or a simple sleep on the function would work.我应该使用 javascript 还是在 function 上简单的睡眠会起作用。

PD: Emails are being sent via $_SESSION variables on php. PD:电子邮件正在通过 php 上的$_SESSION变量发送。

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.您可以为此使用 cron 作业(如果您的托管环境允许您定义一个),或者跟踪您上次自己发送电子邮件的时间。

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:有关 Cron 及其使用方法,请参阅:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM