Aug 29, 2024 8 minute read
How to write Emails with Laravel
Table of Contents
- Prerequisites
- Getting Started
- Creating a Mailable Class
- Creating Email Templates
- Sending Emails
- Handling Common Email Features
- Best Practices for Sending Emails
- Useful Links
Sending emails is a common task in web development, whether it's sending a welcome message to new users, order confirmations, or notifications in general. Laravel 11 simplifies the process of sending emails with its powerful built-in email functionalities.
Prerequisites
Before diving into email sending in Laravel 11, you should be familiar with:
- Basic PHP knowledge.
- Setting up a Laravel project.
- How to use Laravel Artisan commands.
If you haven't installed Laravel 11 yet, you can do so by following the official documentation.
Getting started
To start sending emails with Laravel, you'll need to create a new Laravel project, or you can add onto an existing project.
Setting up Email Configuration
Laravel uses the config/mail.php
file to manage email configuration. However, most of the configuration is done via the .env
file.
Laravel also allows you to configure different email settings for various environments, making it easy to use a different mail setup for development and production.
Configuring the .env File for Development
For development purposes, it's often safer to use a tool like Mailtrap. If you're using Laravel Herd Pro, you can also use its local email service, which helps you test and debug emails.
Mailtrap
Mailtrap captures emails sent by your application, so you can review them without sending them to actual users.
To use Mailtrap, you'll need to sign up for an account and get the MAIL_USERNAME
and MAIL_PASSWORD
from your Mailtrap dashboard.
To set that up, open your .env
file and configure the following settings:
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@yourapp.local"
MAIL_FROM_NAME="${APP_NAME}"
Herd
Herd Pro provides an SMTP mail server on your local machine that catches all outgoing emails of your application and displays them in an internal email client. The mail server uses the SMTP protocol to accept mails but instead of sending them to their recipient, it saves them to an internal database.
To receive mails in the Herd Pro mail UI, you need to use the following settings in your .env
file:
MAIL_MAILER=smtp
MAIL_HOST=127.0.0.1
MAIL_PORT=2525
MAIL_USERNAME=${APP_NAME}
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
For more information on Herd's email service, check their official documentation.
Configuring the .env File for Production (Gmail SMTP)
For sending real emails in production, you can configure your Laravel application to use Gmail's SMTP server. This is particularly useful for small applications or during early stages of deployment.
Important: If you're using Gmail, you'll need to generate an App Password instead of using your regular Gmail password. This is because Gmail blocks the use of regular passwords for SMTP because of security reasons.
You can create an App Password by enabling 2-Step Verification and generating the password in your Google account settings under "App Passwords". For a better explanation, check out this blog post by Mailtrap.
Here’s how you can configure your .env
file for Gmail:
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your_gmail_username@gmail.com
MAIL_PASSWORD=your_gmail_app_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS="your_gmail_username@gmail.com"
MAIL_FROM_NAME="${APP_NAME}"
Switching Between Development and Production Configurations
To switch between development and production environments, simply update the .env
file on your production server with the Gmail SMTP settings. For local development, stick with the Mailtrap configuration.
Choosing an Email Service Provider
There are various email service providers you can integrate with Laravel, such as:
- Mailtrap: Ideal for testing emails during development.
- SendGrid: A popular choice for sending emails in production.
- Mailgun: Another reliable service, especially for large-scale applications.
Creating a Mailable Class
Laravel's Mailable classes make it easy to create and send emails. To create a new Mailable class, you can use the Artisan command:
php artisan make:mail WelcomeEmail
This command will generate a new class in the App\Mail directory.
Structuring the Mailable Class
Here’s an example of how you can structure your Mailable class:
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->view('emails.welcome')
->with(['user' => $this->user])
->subject('Welcome to Our Platform');
}
}
This class uses the view()
method to specify the email template and passes data (in this case, a user object) to the view.
Creating Email Templates
Laravel uses Blade templates for creating email views, which makes it easy to manage your email's structure.
Basic HTML Email Template
Create a new Blade file for your email in the resources/views/emails
directory:
<!-- resources/views/emails/welcome.blade.php -->
<html>
<body>
<h1>Hello, {{ $user->name }}!</h1>
<p>Welcome to our platform. We're excited to have you on board.</p>
</body>
</html>
This template is simple but effective. You can style it further using inline CSS or include assets like images.
Markdown Emails
Laravel also supports Markdown for creating email templates. This is great for creating clean, responsive emails quickly.
You can generate a Markdown Mailable class like this:
php artisan make:mail WelcomeEmail --markdown=emails.welcome
Laravel provides a markdown()
method in the Mailable class to send Markdown-based emails.
Sending Emails
Now that you've created your Mailable class and template, let's send an email.
Sending Emails Synchronously
To send an email directly (synchronously), use the following code in your controller or service:
use App\Mail\WelcomeEmail;
use Illuminate\Support\Facades\Mail;
$user = User::find(1);
Mail::to($user->email)->send(new WelcomeEmail($user));
This will immediately send the email to the specified recipient.
Sending Emails Asynchronously (Using Queues)
For better performance, especially in production, you can send emails asynchronously by queuing them:
Code kopieren
Mail::to($user->email)->queue(new WelcomeEmail($user));
Laravel queues allow your application to handle other tasks while the email is being sent in the background.
Configuring Queues
To set up queues, you need to configure a queue driver in your .env file:
QUEUE_CONNECTION=database
Then, run the migration to create the necessary database table:
php artisan queue:table
php artisan migrate
Start the queue worker to begin processing jobs:
php artisan queue:work
And that's it, now you can send emails with Laravel!
Handling Common Email Features
Adding Attachments
You can easily attach files to your emails using the attach()
method:
public function build()
{
return $this->view('emails.welcome')
->attach(public_path('files/invoice.pdf'));
}
Multiple Recipients
Laravel also supports sending emails to multiple recipients, including CC and BCC:
Mail::to($user->email)
->cc('another@example.com')
->bcc('hidden@example.com')
->send(new WelcomeEmail($user));
Best Practices for Sending Emails
-
Email Security: Always store sensitive information like email passwords and API keys in your
.env
file rather than hard-coding them. - Responsive Design: Ensure your email templates are responsive and look good on all devices.