Skip to content

Instantly share code, notes, and snippets.

@FabianSchmick
Last active January 31, 2019 13:25
Show Gist options
  • Save FabianSchmick/ab1d0db200ecc5ff6e8d0e084a2c3b8b to your computer and use it in GitHub Desktop.
Save FabianSchmick/ab1d0db200ecc5ff6e8d0e084a2c3b8b to your computer and use it in GitHub Desktop.
Log swiftmailer mails in eml files
<?php
namespace AppBundle\Util;
use Gedmo\Sluggable\Util as Sluggable;
use Swift_Events_SendEvent;
use Swift_Events_SendListener;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
use Symfony\Component\Filesystem\Filesystem;
/**
* https://stackoverflow.com/q/18033210/5947371
*/
class MailerLoggerUtil implements Swift_Events_SendListener
{
protected $logDir;
/**
* MailerLoggerUtil constructor.
*
* @param string $logDir
*/
public function __construct($logDir)
{
$this->logDir = $logDir;
}
/**
* @param Swift_Events_SendEvent $evt
*/
public function beforeSendPerformed(Swift_Events_SendEvent $evt)
{
// ...
}
/**
* @param Swift_Events_SendEvent $evt
*/
public function sendPerformed(Swift_Events_SendEvent $evt)
{
$message = $evt->getMessage();
$emails = implode(', ', array_keys($message->getTo()));
/**
* Replace this with your own slug function if you don't have Sluggable Util
*/
$emailSlug = $slug = Sluggable\Urlizer::urlize($emails, '-');
$subjectSlug = $slug = Sluggable\Urlizer::urlize($message->getSubject(), '-');
$dir = $this->logDir.'/mail/'.date('Y/m/d');
$file = date('Ymd_His').'_'.$emailSlug.'_'.$subjectSlug.'.eml';
$fileSystem = new Filesystem();
try {
$fileSystem->mkdir($dir);
} catch (IOExceptionInterface $exception) {
echo "An error occurred while creating your directory at ".$exception->getPath();
}
file_put_contents($dir.'/'.$file, $message->toString());
}
}
services:
_defaults:
bind:
$logDir: '%kernel.logs_dir%'
AppBundle\Util\MailerLoggerUtil:
tags:
- { name: monolog.logger, channel: mailer }
- { name: "swiftmailer.default.plugin" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment