Sending Emails in Laravel
Sending Emails in Laravel
Laravel provides a clean, simple API for sending emails, making it easy to implement email functionality in your applications. It uses the Mail facade to send emails via different drivers like SMTP, Mailgun, Postmark, Amazon SES, and others. Below is a comprehensive guide on how to send emails in Laravel.
1. Setting Up the Mail Configuration
Before sending emails, you need to configure your mail settings. These settings are stored in the .env
file.
Example: Mail Configuration in .env
MAIL_MAILER=smtp MAIL_HOST=smtp.mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=your_username MAIL_PASSWORD=your_password MAIL_ENCRYPTION=null MAIL_FROM_ADDRESS=noreply@example.com MAIL_FROM_NAME="${APP_NAME}"
MAIL_MAILER
: Specifies the mail driver (e.g.,smtp
,sendmail
,mailgun
).MAIL_HOST
: The SMTP server address.MAIL_PORT
: The port number for the SMTP server.MAIL_USERNAME
: The username for SMTP authentication.MAIL_PASSWORD
: The password for SMTP authentication.MAIL_ENCRYPTION
: The encryption protocol (e.g.,tls
,ssl
).MAIL_FROM_ADDRESS
: The default sender's email address.MAIL_FROM_NAME
: The default sender's name.
2. Creating Mailable Classes
Laravel uses Mailable classes to represent an email message. You can create a Mailable class using the Artisan command:
php artisan make:mail OrderShipped
This command generates a new Mailable class in the app/Mail
directory.
Example: Mailable Class (app/Mail/OrderShipped.php
)
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class OrderShipped extends Mailable
{
use Queueable, SerializesModels;
public $order;
public function __construct($order)
{
$this->order = $order;
}
public function build()
{
return $this
->subject('Your Order Has Shipped')
->view('emails.orders.shipped');
}
}
use Queueable, SerializesModels
: These traits help in handling queue jobs and serialization of models.public $order
: This public property allows you to pass data to your email view.build()
: This method defines the email subject, view, and any other configurations.
3. Creating the Email View
Create a Blade view for your email in the resources/views/emails/orders/
directory.
Example: Email View (resources/views/emails/orders/shipped.blade.php
)
<!DOCTYPE html> <html> <head> <title>Order Shipped</title> </head> <body> <h1>Your Order has Shipped!</h1> <p>Order ID: {{ $order->id }}</p> <p>Thank you for your purchase!</p> </body> </html>
4. Sending the Email
You can send an email using the Mail
facade. Here’s an example of how to send an email when an order is shipped.
Example: Sending the Email in a Controller
use App\Mail\OrderShipped;
use Illuminate\Support\Facades\Mail;
public function shipOrder($orderId)
{
$order = Order::findOrFail($orderId);
// Send the email
Mail::to($order->user->email)->send(new OrderShipped($order));
return response()->json(['message' => 'Order shipped email sent.']);
}
5. Queueing Emails
For performance reasons, it’s often best to queue emails to be sent later, especially for long-running processes. Laravel provides built-in support for queued emails.
Step 1: Configuring the Queue
First, make sure you have a queue driver set up in your .env
file, such as database
, redis
, or another supported driver.
QUEUE_CONNECTION=database
Step 2: Sending Queued Emails
To send a Mailable class as a queued job, use the queue()
method instead of send()
.
Mail::to($order->user->email)->queue(new OrderShipped($order));
6. Testing Emails
You can use Mailtrap or similar services for testing email sending without sending real emails. Laravel integrates easily with Mailtrap, which is useful during development.
Step 1: Configure Mailtrap
Update your .env
file to use Mailtrap:
MAIL_MAILER=smtp MAIL_HOST=smtp.mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=your_mailtrap_username MAIL_PASSWORD=your_mailtrap_password MAIL_ENCRYPTION=null MAIL_FROM_ADDRESS=noreply@example.com MAIL_FROM_NAME="${APP_NAME}"
7. Markdown Emails
Laravel also supports Markdown for creating styled email templates. You can generate a Markdown email using the following command:
php artisan make:mail OrderShipped --markdown=emails.orders.shipped
Example: Markdown Email View (resources/views/emails/orders/shipped.blade.php
)
@component('mail::message') # Your Order has Shipped! Order ID: {{ $order->id }} Thank you for your purchase! @component('mail::button', ['url' => '']) View Order @endcomponent Thanks,<br> {{ config('app.name') }} @endcomponent
8. Customizing the Mail Configuration
You can customize the mail settings on a per-mail basis using the with()
method in the build()
function of the Mailable class. This allows you to pass additional data to your view.