How to change SwiftMailer temporary folder in Laravel

Sometimes if you sending a lot of emails, it can make /tmp/ folder very quickly filled up with cache file, and in my case it make the Apache and MySQL failed to start. The message error in Apache error_log is Fatal Error Unable to create lock file: Bad file descriptor (9).

In Laravel you can change the swiftmailer temporary folder, for example in storage/app/ folder.

We can set it boot() method in AppServiceProvider file :

app/Providers/AppServiceProvider.php

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
       /**
         * Somehow PHP is not able to write in default /tmp directory 
         * and SwiftMailer was failing.
         * To overcome this situation, we set the TMPDIR environment 
         * variable to a new value.
         */
        if (class_exists('Swift_Preferences')) {
            \Swift_Preferences::getInstance()->setTempDir(storage_path('app/tmp/'));
        } else {
            \Log::warning('Class Swift_Preferences does not exists');
        }
    }
}

0 thoughts on “How to change SwiftMailer temporary folder in Laravel

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>