Skip to content

Instantly share code, notes, and snippets.

@DracoBlue
Last active August 29, 2015 13:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DracoBlue/9468262 to your computer and use it in GitHub Desktop.
Save DracoBlue/9468262 to your computer and use it in GitHub Desktop.
Very simple but fast (file based) mail queue
<?php
class MailQueueService()
{
public function getMailsFolder()
{
return '/tmp/mails/';
}
public function popSpooledMail()
{
foreach (new DirectoryIterator($this->getMailsFolder()) as $file_info) {
if($file_info->isDot()) continue;
if ($file_info->getExtension() == 'json')
{
$file_path = $file_info->getPathname();
$content = @file_get_contents($file_path);
if ($content)
{
if (@unlink($file_path))
{
return json_decode($content, true);
}
}
}
}
throw new \Exception('No mail in the queue!');
}
public function pushMail($values)
{
file_put_contents($this->generateUniqueFileNameForSpooledMail(), json_encode($values));
}
protected function generateUniqueFileNameForSpooledMail()
{
$uuid = substr(sha1(uniqid('', true) . microtime(true)), 0, 32);
$file_name = $this->getMailsFolder() . $uuid . '.json';
while (file_exists($file_name))
{
$uuid = substr(sha1(uniqid('', true) . microtime(true)), 0, 32);
$file_name = $this->getMailsFolder() . $uuid . '.json';
}
return $file_name;
}
}
<?php
$queue = new \MailQueueService();
$queue->pushMail(array('subject' => 'hai', 'body' => 'hai body', 'email' => 'hans@example.org'));
$queue->pushMail(array('subject' => 'hai2', 'body' => 'hai body', 'email' => 'hans@example.org'));
$queue->pushMail(array('subject' => 'hai3', 'body' => 'hai body', 'email' => 'hans@example.org'));
$count = 5;
try
{
while ($count > 0)
{
$mail_values = $queue->popSpooledMail();
/* FIXME: code to send the mail values */
$count--;
}
} catch (\Exception $exception)
{
/* done! */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment