Before sending emails, you need to configure your mail settings. Laravel provides several drivers, such as SMTP, Mailgun, and Postmark. The configuration is stored in the .env
file.
Example: Configuration in .env
File
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=no-reply@example.com
MAIL_FROM_NAME="${APP_NAME}"
In Laravel, you can create a "Mailable" class that will represent the email being sent. Use the Artisan command to generate this class.
Example: Creating a Mailable Class
php artisan make:mail WelcomeEmail
In the generated WelcomeEmail.php
file, you can define the email content, subject, and other parameters.
Example: Mailable Class Definition
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class WelcomeEmail extends Mailable
{
use Queueable, SerializesModels;
public $user;
public function __construct($user)
{
$this->user = $user;
}
public function build()
{
return $this->subject('Welcome to Our Platform')
->view('emails.welcome')
->with(['name' => $this->user->name]);
}
}
The next step is to create the email content view. You can use Blade templates for this.
Example: Creating Email View
Create a Blade file in resources/views/emails/welcome.blade.php
:
<!DOCTYPE html>
<html>
<head>
<title>Welcome to Our Platform</title>
</head>
<body>
<h1>Hello, {{ $name }}</h1>
<p>Thank you for joining our platform. We are excited to have you!</p>
</body>
</html>
To send the email, you can use the Mail
facade and the to()
method, specifying the recipient's email address.
Example: Sending the Email
use App\Mail\WelcomeEmail;
use Illuminate\Support\Facades\Mail;
public function sendWelcomeEmail($user)
{
Mail::to($user->email)->send(new WelcomeEmail($user));
}
For performance reasons, especially with large volumes of emails, you might want to queue the email instead of sending it immediately.
Example: Queueing the Email
In the WelcomeEmail
mailable class, add the ShouldQueue
interface:
use Illuminate\Contracts\Queue\ShouldQueue;
class WelcomeEmail extends Mailable implements ShouldQueue
{
// Existing code
}
You can test your email functionality in a local development environment using services like Mailtrap or by setting up SMTP with your own email provider.
Example: Testing Email
Ensure your .env
configuration is set to use a test email service like Mailtrap and check your inbox for the sent email.
Laravel provides an easy-to-use mail system that allows you to send personalized emails quickly. With features like Mailables, email views, and queueing, you can build and send robust email systems for notifications, confirmations, and more. Simply configure your mail settings, create a mailable class, build the content, and send it!