E-Mails

E-Mails

With Laravel its pretty easy to send mails. So let’s go over the different steps.

Generating a Mailable

Create a mailable class with Artisan:

Bash
php artisan make:mail JobPosted

This creates a class in app/Mail/JobPosted.php where you can define:

  • Envelope: Set email subject, sender, reply-to, and tags.
  • Content: Specify the Blade view for the email body.
  • Attachments: Add files if needed.

Creating the Email View

Create a Blade view in resources/views/mail/job-posted.blade.php with your email content:

PHP
<p>Congrats, your job is now live on our website.</p>

Previewing the Email

Add a temporary route to return the mailable for preview:

PHP
Route::get('/test', function () {
    return new \App\Mail\JobPosted();
});

Visit /test in your browser to see the email rendered.

Sending Emails

Use the Mail facade to send emails:

PHP
use Illuminate\Support\Facades\Mail;

Mail::to('jeffrey@laracasts.com')->send(new \App\Mail\JobPosted());

By default, in local environments without SMTP configured, emails are logged to storage/logs/laravel.log. Or if you use Laravel Herd Pro it will open an inbox automatically, since with Pro it has a mail server included.

Configuring Mail Settings

Edit config/mail.php or your .env file to set mail driver, SMTP host, port, username, and password.

Example for Mailtrap (a popular testing service):

PHP
MAIL_MAILER=smtp
MAIL_HOST=sandbox.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_FROM_ADDRESS=info@laracasts.com
MAIL_FROM_NAME="Laracasts"

Passing Data to Mailables

You can pass data to your mailable’s constructor and expose it as public properties for use in the email view:

PHP
public $job;

public function __construct(Job $job)
{
    $this->job = $job;
}

In the Blade view, access $job to display dynamic content.

Generating URLs in Emails

Use Laravel’s url() helper to generate full URLs in emails:

PHP
<a href="{{ url('jobs/' . $job->id) }}">View your job listing</a>

This ensures URLs work in both local and production environments.

Tags: