Blog postSend mail with Laravel

Send mail with Laravel

Published November 05, 2021

If you use PHP as a professional you probably use Laravel as a framework and one of the most important things to do for any website is sending emails. In this tutorial we'll explain how to send emails from Laravel in 3 easy steps.

# How to send mail with Laravel?

1. Define the email address for your website in the configuration file config/constants.php.

return [
  'FROM_MAIL'      => '',
  'FROM_MAIL_NAME' => 'my_website_name',

2. In the method from which you want to send the email, collect the data that you want to send into an array, and pass this into the method Mail::send.

// Collect the data to the $emailData array
$emailData = [
  'id'     => $id,
  'name'   => $data['name'],
  'email'  => $data['email'],
  'text'   => $data['description'],

// Use Laravel's send method
\Mail::send('emails.new_msg', $emailData, function ($message) use ($emailData) {
  $message->from(config('constants.FROM_MAIL'), config('constants.FROM_MAIL_NAME'));

  $msgSubject = "New message id #" . $emailData['id'];

3. Embed the items keys from the above array as variables in your email's template:

// resources/views/emails/new_msg.blade.php
Id: {{$id}}
Name: {{$name}}
Email: {{$email}}
Description: {{$text}}

# Conclusion

In this tutorial we have demonstrated how to send emails with Laravel with ease.

comments powered by Disqus