Skip to contentSkip to navigationSkip to topbar
Rate this page:
On this page

Send Email in Laravel


Laravel provides a clean API over the popular SwiftMailer library with drivers for SMTP, PHP's mail, sendmail and more. For this example, we'll be sending a Laravel email with SendGrid using the SMTP Driver. For more information, check out the docs for Laravel's Mail interface(link takes you to an external page).

Laravel 5.5 LTS uses Mailable classes. Mailables in Laravel abstracts building emails with a mailable class. Mailables are responsible for collating data and passing them to views.


Before you begin using Laravel to send email

before-you-begin-using-laravel-to-send-email page anchor

Check your .env file and configure these variables:


_10
MAIL_MAILER=smtp
_10
# MAIL_DRIVER=smtp # for laravel < 7
_10
MAIL_HOST=smtp.sendgrid.net
_10
MAIL_PORT=587
_10
MAIL_USERNAME=apikey
_10
MAIL_PASSWORD=sendgrid_api_key
_10
MAIL_ENCRYPTION=tls
_10
MAIL_FROM_NAME="John Smith"
_10
MAIL_FROM_ADDRESS=from@example.com

(information)

Info

Set the MAIL_USERNAME field to "apikey" to inform SendGrid that you're using an API key.

(information)

Info

The MAIL_FROM_NAME field requires double quotes because there is a space in the string.

(information)

Info

You can send 100 messages per SMTP connection at a time, and open up to 10 concurrent connections from a single server at a time.


(error)

Danger

Categories and Unique Arguments will be stored as a "Not PII" field and may be used for counting or other operations as SendGrid runs its systems. These fields generally cannot be redacted or removed. You should take care not to place PII in this field. SendGrid does not treat this data as PII, and its value may be visible to SendGrid employees, stored long-term, and may continue to be stored after you've left SendGrid's platform.

Next you need to create a Mailable class, Laravel's CLI tool called Artisan makes that a simple feat. Open CLI, go to the project directory and type:

php artisan make:mail TestEmail

This command will create a new file under app/Mail/TestEmail.php and it should look something like this:


_35
<?php
_35
_35
namespace App\Mail;
_35
_35
use Illuminate\Bus\Queueable;
_35
use Illuminate\Mail\Mailable;
_35
use Illuminate\Queue\SerializesModels;
_35
use Illuminate\Contracts\Queue\ShouldQueue;
_35
_35
class TestEmail extends Mailable
_35
{
_35
use Queueable, SerializesModels;
_35
_35
public $data;
_35
_35
public function __construct($data)
_35
{
_35
$this->data = $data;
_35
}
_35
_35
public function build()
_35
{
_35
$address = 'janeexampexample@example.com';
_35
$subject = 'This is a demo!';
_35
$name = 'Jane Doe';
_35
_35
return $this->view('emails.test')
_35
->from($address, $name)
_35
->cc($address, $name)
_35
->bcc($address, $name)
_35
->replyTo($address, $name)
_35
->subject($subject)
_35
->with([ 'test_message' => $this->data['message'] ]);
_35
}
_35
}

In Laravel Views are used as 'templates' when sending an email. Let's create a file under app/resources/views/emails/test.blade.php and insert this code:


_10
<!DOCTYPE html>
_10
<html lang="en-US">
_10
<head>
_10
<meta charset="utf-8" />
_10
</head>
_10
<body>
_10
<h2>Test Email</h2>
_10
<p>{{ $test_message }}</p>
_10
</body>
_10
</html>


Sending an email with Laravel

sending-an-email-with-laravel page anchor

Now that we have our Mailable Class created, all we need to do is run this code to use Laravel to send email:


_10
<?php
_10
use App\Mail\TestEmail;
_10
_10
$data = ['message' => 'This is a test!'];
_10
_10
Mail::to('john@example.com')->send(new TestEmail($data));


Adding a category or custom field

adding-a-category-or-custom-field page anchor

Categories in SendGrid allow you to split your statistics into sections.

Another useful tool is event notifications. If you want to complete the feedback loop for your product you can pass identifiers as a header which relate to a record in your database which you can then parse the notifications against that record to track deliveries/opens/clicks/bounces.

The withSwiftMessage method of the Mailable base class allows you to register the callback that is invoked with the raw SwiftMailer message instance before sending the message. This knowledge allows you to customize the message before delivery. To customize your message, use something similar to this:


_65
<?php
_65
_65
namespace App\Mail;
_65
_65
use Illuminate\Bus\Queueable;
_65
use Illuminate\Mail\Mailable;
_65
use Illuminate\Queue\SerializesModels;
_65
use Illuminate\Contracts\Queue\ShouldQueue;
_65
_65
class TestEmail extends Mailable
_65
{
_65
use Queueable, SerializesModels;
_65
_65
public $data;
_65
_65
public function __construct($data)
_65
{
_65
$this->data = $data;
_65
}
_65
_65
public function build()
_65
{
_65
$address = 'janeexampexample@example.com';
_65
$subject = 'This is a demo!';
_65
$name = 'Jane Doe';
_65
_65
$headerData = [
_65
'category' => 'category',
_65
'unique_args' => [
_65
'variable_1' => 'abc'
_65
]
_65
];
_65
_65
$header = $this->asString($headerData);
_65
_65
$this->withSwiftMessage(function ($message) use ($header) {
_65
$message->getHeaders()
_65
->addTextHeader('X-SMTPAPI', $header);
_65
});
_65
_65
return $this->view('emails.test')
_65
->from($address, $name)
_65
->cc($address, $name)
_65
->bcc($address, $name)
_65
->replyTo($address, $name)
_65
->subject($subject)
_65
->with([ 'data' => $this->data ]);
_65
}
_65
_65
private function asJSON($data)
_65
{
_65
$json = json_encode($data);
_65
$json = preg_replace('/(["\]}])([,:])(["\[{])/', '$1$2 $3', $json);
_65
_65
return $json;
_65
}
_65
_65
_65
private function asString($data)
_65
{
_65
$json = $this->asJSON($data);
_65
_65
return wordwrap($json, 76, "\n ");
_65
}
_65
}


Rate this page: