Home >Backend Development >PHP Tutorial >Mail Logging in Laravel 5.3: Extending the Mail Driver

Mail Logging in Laravel 5.3: Extending the Mail Driver

William Shakespeare
William ShakespeareOriginal
2025-02-10 11:00:16853browse

Laravel 5.3 Mail Send Extension: Custom Database Mail Log

Laravel 5.3 provides an easy way to configure and send emails through a variety of popular services and includes a log assistive program for development. However, it does not cover all available services and may require extension of existing mail driver systems.

Key points:

  • Laravel 5.3 provides an easy way to easily configure and send emails through a variety of popular services, and includes log assistive programs for development. However, it does not cover all available services and may require extension of an existing mail driver system.
  • To extend the mail driver system, you can use the artisan command line assistant to create a new service provider. This service provider interacts with the application and registers the service at startup.
  • The new service provider can extend the existing IlluminateMailMailServiceProvider, allowing the register method to be implemented. This allows the creation of a new Transport Manager that binds a Swift mailer instance to a container.
  • Extended mail driver system can be used to log emails into database tables for debugging. This is done by creating a new migration and a new model for the database table to interact with the table. Then add the provider to the provider list in the config/app.php file and register the mail driver to config/mail.php in the db file.

Mail Logging in Laravel 5.3: Extending the Mail Driver

Laravel provides many practical features, including mail delivery. You can easily configure and send emails through a variety of popular services, and it even includes log assistive programs for development.

<code class="language-php">Mail::send('emails.welcome', ['user' => $user], function ($m) use ($user) {
    $m->to($user->email, $user->name)->subject('Welcome to the website');
});</code>

This will use the emails.welcome view to send emails to newly registered users on the website. Using Mailable in Laravel 5.3, it becomes easier (but the old syntax is still valid).

Mail Logging in Laravel 5.3: Extending the Mail Driver

The following is an example:

<code class="language-bash"># 生成一个新的可邮件类
php artisan make:mail WelcomeMail</code>
<code class="language-php">// app/Mail/WelcomeMail.php

class WelcomeUser extends Mailable
{
    use Queueable, SerializesModels;

    public $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function build()
    {
        return $this->view('emails.welcome');
    }
}</code>
<code class="language-php">// routes/web.php

Route::get('/', function () {
    $user = User::find(2);

    \Mail::to($user->email)->send(new WelcomeUser($user));

    return "done";
});</code>

Laravel also provides a good starting point for sending mail using log drivers during the development phase, and smtp, sparkpost, mailgun, etc. during the production phase. This seems good in most cases, but it doesn't cover all the services available! In this tutorial, we will learn how to extend an existing mail driver system to add our own drivers.

To make our example simple and clear, we log the mail log into the database table.

Create a service provider

The preferred method to achieve this is to create a service provider that can interact with our application and register our services at startup. Let's first generate a new service provider using the artisan command line assistant.

<code class="language-php">Mail::send('emails.welcome', ['user' => $user], function ($m) use ($user) {
    $m->to($user->email, $user->name)->subject('Welcome to the website');
});</code>

This will create a new class in our app/Providers folder. If you are familiar with the Laravel service provider, you will know that we have extended the ServiceProvider class and defined the boot and register methods. You can read more about the provider in the documentation.

Using the mail provider

Instead of using the parent service provider class, we can take shortcuts and extend the existing IlluminateMailMailServiceProvider. This means that the register method has been implemented.

<code class="language-bash"># 生成一个新的可邮件类
php artisan make:mail WelcomeMail</code>
The

registerSwiftMailer method will return the corresponding transfer driver according to the mail.driver configuration value. What we can do here is to perform a check before calling the registerSwiftMailer parent method and return our own transfer manager .

<code class="language-php">// app/Mail/WelcomeMail.php

class WelcomeUser extends Mailable
{
    use Queueable, SerializesModels;

    public $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function build()
    {
        return $this->view('emails.welcome');
    }
}</code>

Using Transfer Manager

Laravel parses the swift.mailer instance from the IOC, which should return the SwiftMailer instance of Swift_Mailer. We need to bind our Swift mailer instance to the container.

<code class="language-php">// routes/web.php

Route::get('/', function () {
    $user = User::find(2);

    \Mail::to($user->email)->send(new WelcomeUser($user));

    return "done";
});</code>

You can treat the transfer object as the actual driver. If you check the IlluminateMailTransport namespace, you will find different transport classes for each driver (for example: LogTransport, SparkPostTransport, etc.).

The

Swift_Mailer class requires a Swift_Transport instance, which we can satisfy by extending the IlluminateMailTransportTransport class. It should look like this.

<code class="language-bash">php artisan make:provider DBMailProvider</code>

The only way we should implement here is the send method. It is responsible for the mail sending logic, in which case it should log our emails to the database. As for our constructor, we can leave it blank for now, because we don't need any external dependencies.

The

$message->getTo() method always returns an associative array of recipient email and name. We use the array_keys function to get the email list and then merge them to get the string.

Record email to database

The next step is to create the necessary migrations for our database tables.

<code class="language-php">// vendor/Illuminate/Mail/MailServiceProvider.php

public function register()
{
    $this->registerSwiftMailer();

    // ...
}</code>
<code class="language-php">// app/Providers/DBMailProvider.php

function registerSwiftMailer()
{
    if ($this->app['config']['mail.driver'] == 'db') {
        $this->registerDBSwiftMailer();
    } else {
        parent::registerSwiftMailer();
    }
}</code>

Our migration only contains email body, subject and recipient email, but you can add more details as needed. Check the Swift_Mime_Message class definition to see a list of available fields.

Now, we need to create a new model to interact with our table and add the necessary fields to the fillable array.

<code class="language-php">Mail::send('emails.welcome', ['user' => $user], function ($m) use ($user) {
    $m->to($user->email, $user->name)->subject('Welcome to the website');
});</code>
<code class="language-bash"># 生成一个新的可邮件类
php artisan make:mail WelcomeMail</code>

Send an email

Okay, now is the time to test what we have achieved so far. We first add our provider to the list of providers in the config/app.php file.

<code class="language-php">// app/Mail/WelcomeMail.php

class WelcomeUser extends Mailable
{
    use Queueable, SerializesModels;

    public $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function build()
    {
        return $this->view('emails.welcome');
    }
}</code>

Then we register the mail driver in config/mail.php in the db file.

<code class="language-php">// routes/web.php

Route::get('/', function () {
    $user = User::find(2);

    \Mail::to($user->email)->send(new WelcomeUser($user));

    return "done";
});</code>

The only remaining part is sending a test email and checking if it is logged into the database. I'll send an email when I access the homepage URL. The following is the code.

<code class="language-bash">php artisan make:provider DBMailProvider</code>

After accessing the homepage route, we can run the php artisan tinker command to check the emails table record.

Mail Logging in Laravel 5.3: Extending the Mail Driver

Conclusion

In this article, we see how to extend the mail driver system to intercept emails for debugging. One thing I appreciate in Laravel is its unparalleled scalability: You can change or extend everything from routers and IOCs to mail and just about everything else.

If you have any questions or comments, please be sure to post them below and I will try my best to answer!

FAQs about mail logging in Laravel 5.3 (FAQ)

How to extend the mail driver in Laravel 5.3?

Extending the mail driver in Laravel 5.3 involves creating a new service provider. This service provider will extend the existing mail driver and allow you to add additional features. You can use the php artisan make:provider command to create a new service provider. After creating the provider, you can register it in the config/app.php file. In the provider, you can use the extend method to add custom functionality to the mail driver.

What is the purpose of mail logging in Laravel?

Mail logging in Laravel is a feature that allows you to track all outgoing emails sent by your application. This is very useful for debugging because it allows you to see exactly which emails are being sent, when and to whom. It is also very useful for auditing because it provides a record of all email communications sent by the application.

How to configure Laravel to log all outgoing emails?

To configure Laravel to record all outgoing emails, you need to modify the config/mail.php file. In this file, you can set the log option to true. This instructs Laravel to log all outgoing emails. The logs will be stored in the storage/logs directory.

How to view email logs in Laravel?

The mail logs in Laravel are stored in the storage/logs directory. You can view these logs by navigating to this directory and opening the log file. The log files are named according to dates, so you can easily find logs for specific dates.

Can I customize the format of email logs in Laravel?

Yes, you can customize the format of mail logs in Laravel. This can be done by extending the mail driver and overriding the log method. In this method, you can specify the format of the log message.

(The rest of the FAQ is related to the email sending itself, and has nothing to do with the email log extension in this example, so it is omitted)

Please note that the image paths /uploads/20250210/173915090467a9563807841.webp and /uploads/20250210/173915090467a9563839bfc.webp and /uploads/20250210/173915090667a9563a27b41.jpg need to be replaced with actual accessible image links.

The above is the detailed content of Mail Logging in Laravel 5.3: Extending the Mail Driver. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn