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 theregister
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 toconfig/mail.php
in thedb
file.
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.
Mail::send('emails.welcome', ['user' => $user], function ($m) use ($user) { $m->to($user->email, $user->name)->subject('Welcome to the website'); });
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).
The following is an example:
# 生成一個(gè)新的可郵件類 php artisan make:mail WelcomeMail
// 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'); } }
// routes/web.php Route::get('/', function () { $user = User::find(2); \Mail::to($user->email)->send(new WelcomeUser($user)); return "done"; });
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.
Mail::send('emails.welcome', ['user' => $user], function ($m) use ($user) { $m->to($user->email, $user->name)->subject('Welcome to the website'); });
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.
# 生成一個(gè)新的可郵件類 php artisan make:mail WelcomeMailThe
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 .
// 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'); } }
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.
// routes/web.php Route::get('/', function () { $user = User::find(2); \Mail::to($user->email)->send(new WelcomeUser($user)); return "done"; });
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.).
Swift_Mailer
class requires a Swift_Transport
instance, which we can satisfy by extending the IlluminateMailTransportTransport
class. It should look like this.
php artisan make:provider DBMailProvider
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.
$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.
// vendor/Illuminate/Mail/MailServiceProvider.php public function register() { $this->registerSwiftMailer(); // ... }
// app/Providers/DBMailProvider.php function registerSwiftMailer() { if ($this->app['config']['mail.driver'] == 'db') { $this->registerDBSwiftMailer(); } else { parent::registerSwiftMailer(); } }
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.
Mail::send('emails.welcome', ['user' => $user], function ($m) use ($user) { $m->to($user->email, $user->name)->subject('Welcome to the website'); });
# 生成一個(gè)新的可郵件類 php artisan make:mail WelcomeMail
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.
// 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'); } }
Then we register the mail driver in config/mail.php
in the db
file.
// routes/web.php Route::get('/', function () { $user = User::find(2); \Mail::to($user->email)->send(new WelcomeUser($user)); return "done"; });
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.
php artisan make:provider DBMailProvider
After accessing the homepage route, we can run the php artisan tinker
command to check the emails
table record.
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

To determine the strength of the password, it is necessary to combine regular and logical processing. The basic requirements include: 1. The length is no less than 8 digits; 2. At least containing lowercase letters, uppercase letters, and numbers; 3. Special character restrictions can be added; in terms of advanced aspects, continuous duplication of characters and incremental/decreasing sequences need to be avoided, which requires PHP function detection; at the same time, blacklists should be introduced to filter common weak passwords such as password and 123456; finally it is recommended to combine the zxcvbn library to improve the evaluation accuracy.

To merge two PHP arrays and keep unique values, there are two main methods. 1. For index arrays or only deduplication, use array_merge and array_unique combinations: first merge array_merge($array1,$array2) and then use array_unique() to deduplicate them to finally get a new array containing all unique values; 2. For associative arrays and want to retain key-value pairs in the first array, use the operator: $result=$array1 $array2, which will ensure that the keys in the first array will not be overwritten by the second array. These two methods are applicable to different scenarios, depending on whether the key name is retained or only the focus is on

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

There are two ways to create an array in PHP: use the array() function or use brackets []. 1. Using the array() function is a traditional way, with good compatibility. Define index arrays such as $fruits=array("apple","banana","orange"), and associative arrays such as $user=array("name"=>"John","age"=>25); 2. Using [] is a simpler way to support since PHP5.4, such as $color
