Introduction
Sending emails is a common feature in modern web applications, and Laravel makes it super easy with its built-in Mailable class. In this guide, we’ll see how to send emails in Laravel and design a custom email template using Blade.
Step 1: Configure Mail Settings
First, open the .env file in your Laravel project and add your email service provider credentials:
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your-email@example.com
MAIL_PASSWORD=your-email-password/app password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=your-email@example.com
MAIL_FROM_NAME="Your App Name"
💡 If you are using Gmail, make sure to enable "App Passwords" for secure authentication.
Step 2: Create a Mailable Class
Run the following command:
php artisan make:mail WelcomeMail
This will create a file app/Mail/WelcomeMail.php. Update it like this:
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class WelcomeMail extends Mailable
{
use Queueable, SerializesModels;
public $details;
public function __construct($details)
{
$this->details = $details;
}
public function build()
{
return $this->subject('Welcome to Our Application')
->view('emails.welcome');
}
}
Step 3: Create the Email Template
Create a new Blade file at resources/views/emails/welcome.blade.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Welcome Email</title>
</head>
<body style="font-family: Arial, sans-serif; background-color: #f8f8f8; padding: 20px;">
<div style="max-width: 600px; margin: auto; background: white; padding: 20px; border-radius: 8px;">
<h2 style="color: #333;">Hello, {{ $details['name'] }}!</h2>
<p>Welcome to our application. We are excited to have you onboard.</p>
<p><strong>Message:</strong> {{ $details['message'] }}</p>
<a href="{{ $details['link'] }}" style="display: inline-block; background: #3490dc; color: white; padding: 10px 15px; text-decoration: none; border-radius: 5px;">Visit Our Website</a>
</div>
</body>
</html>
Step 4: Sending the Email
You can send the email from a controller like this:
use App\Mail\WelcomeMail;
use Illuminate\Support\Facades\Mail;
public function sendWelcomeEmail()
{
$details = [
'name' => 'John Doe',
'message' => 'Thank you for joining us!',
'link' => 'https://z1iinnovation.com'
];
Mail::to('user@example.com')->send(new WelcomeMail($details));
return "Email Sent!";
}
Step 5: Test the Email
Visit the route where you call the sendWelcomeEmail() method. If your mail configuration is correct, the email should be delivered instantly.
Conclusion
With just a few steps, you can send beautifully designed emails in Laravel. You can enhance the template with CSS styles, images, and even responsive layouts for better presentation.