Search code examples
phplaravel-4swiftmailer

How to unlink files after they have been attached and sent? (When using Mail::queue)


I switched from sending my mails immediately to adding them to the queue, here is my code, the $attachments is an array of temporary paths, I've commented out what I've tried, which throws errors about files not existing.

Mail::queue($view, $data, function(\Illuminate\Mail\Message $message) use($mail,$attachments){
    foreach($mail->getRecipients() as $recipient){
        $message->to($recipient);
    }
    $message->subject($mail->getSubject());
    foreach($attachments as $attachment){
        $message->attach($attachment);
        //this deletes the attachment before being sent
        //unlink($attachment);
    }
});
/* This code only works when using Mail::send() instead of Mail:queue()
foreach($attachments as $attachment){
    unlink($attachment);
}
*/

Basically I want to clean up and remove my temporary attachments after the mail was sent. I am guessing this would not work with the out of the box laravel mail solutions. How can I trigger code post-queue-mail-sent?


Solution

  • You have to wait until the queue is processed before removing the file.

    Without knowing the implementation details of the queue it is hard to answer your question, but if your queue is processed before the script ends, you can use register_shutdown_function http://www.php.net/manual/en/function.register-shutdown-function.php to run a cleanup function that removes the file

    register_shutdown_function(function() use (filename){
        if (file_exists($filename)) {
            unlink($filename);
        }
    })