Last active
January 31, 2019 13:25
-
-
Save FabianSchmick/ab1d0db200ecc5ff6e8d0e084a2c3b8b to your computer and use it in GitHub Desktop.
Log swiftmailer mails in eml files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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