Skip to contentSkip to navigationSkip to topbar
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:

1
MAIL_MAILER=smtp
2
# MAIL_DRIVER=smtp # for laravel < 7
3
MAIL_HOST=smtp.sendgrid.net
4
MAIL_PORT=587
5
MAIL_USERNAME=apikey
6
MAIL_PASSWORD=sendgrid_api_key
7
MAIL_ENCRYPTION=tls
8
MAIL_FROM_NAME="John Smith"
9
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. Open the 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:

1
<?php
2
3
namespace App\Mail;
4
5
use Illuminate\Bus\Queueable;
6
use Illuminate\Mail\Mailable;
7
use Illuminate\Queue\SerializesModels;
8
use Illuminate\Contracts\Queue\ShouldQueue;
9
10
class TestEmail extends Mailable
11
{
12
use Queueable, SerializesModels;
13
14
public $data;
15
16
public function __construct($data)
17
{
18
$this->data = $data;
19
}
20
21
public function build()
22
{
23
$address = 'janeexampexample@example.com';
24
$subject = 'This is a demo!';
25
$name = 'Jane Doe';
26
27
return $this->view('emails.test')
28
->from($address, $name)
29
->cc($address, $name)
30
->bcc($address, $name)
31
->replyTo($address, $name)
32
->subject($subject)
33
->with([ 'test_message' => $this->data['message'] ]);
34
}
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:

1
<!DOCTYPE html>
2
<html lang="en-US">
3
<head>
4
<meta charset="utf-8" />
5
</head>
6
<body>
7
<h2>Test Email</h2>
8
<p>{{ $test_message }}</p>
9
</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:

1
<?php
2
use App\Mail\TestEmail;
3
4
$data = ['message' => 'This is a test!'];
5
6
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:

1
<?php
2
3
namespace App\Mail;
4
5
use Illuminate\Bus\Queueable;
6
use Illuminate\Mail\Mailable;
7
use Illuminate\Queue\SerializesModels;
8
use Illuminate\Contracts\Queue\ShouldQueue;
9
10
class TestEmail extends Mailable
11
{
12
use Queueable, SerializesModels;
13
14
public $data;
15
16
public function __construct($data)
17
{
18
$this->data = $data;
19
}
20
21
public function build()
22
{
23
$address = 'janeexampexample@example.com';
24
$subject = 'This is a demo!';
25
$name = 'Jane Doe';
26
27
$headerData = [
28
'category' => 'category',
29
'unique_args' => [
30
'variable_1' => 'abc'
31
]
32
];
33
34
$header = $this->asString($headerData);
35
36
$this->withSwiftMessage(function ($message) use ($header) {
37
$message->getHeaders()
38
->addTextHeader('X-SMTPAPI', $header);
39
});
40
41
return $this->view('emails.test')
42
->from($address, $name)
43
->cc($address, $name)
44
->bcc($address, $name)
45
->replyTo($address, $name)
46
->subject($subject)
47
->with([ 'data' => $this->data ]);
48
}
49
50
private function asJSON($data)
51
{
52
$json = json_encode($data);
53
$json = preg_replace('/(["\]}])([,:])(["\[{])/', '$1$2 $3', $json);
54
55
return $json;
56
}
57
58
59
private function asString($data)
60
{
61
$json = $this->asJSON($data);
62
63
return wordwrap($json, 76, "\n ");
64
}
65
}

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.