Skip to content
This repository was archived by the owner on Aug 27, 2021. It is now read-only.

Commit e27ebb3

Browse files
author
Kaylyn Sigler
authored
Merge pull request #3035 from Braunson/develop
Updated Laravel Framework Integration Documentation
2 parents 5545c38 + 370d0b8 commit e27ebb3

File tree

1 file changed

+145
-39
lines changed

1 file changed

+145
-39
lines changed

source/Integrate/Frameworks/laravel.md

Lines changed: 145 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -4,83 +4,189 @@ weight: 0
44
title: Laravel
55
seo:
66
title: Send Email with Laravel & SendGrid
7-
description: View instructions on how to easily send email with Laravel using SendGrid, by setting up setting up Laravel's built in mailer.
7+
description: View instructions on how to easily send email with Laravel using SendGrid, by setting up setting up Laravel's Mailables Class.
88
navigation:
99
show: true
1010
---
1111

12-
Laravel comes with an email sending library built in, so we just need to set it to use SendGrid over SMTP. Check out the docs for [Laravel's mailer](http://laravel.com/docs/mail) for details.
12+
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 an email with SendGrid using the SMTP Driver. For more information, check out the docs for [Laravel's Mail interface](http://laravel.com/docs/mail).
1313

14-
In `app/config/mail.php` you need to configure these settings:
14+
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.
15+
16+
{% anchor h2 %}
17+
Before you begin
18+
{% endanchor %}
19+
20+
In `.env` you need to find and configure these variables:
21+
22+
{% codeblock %}
23+
MAIL_DRIVER=smtp
24+
MAIL_HOST=smtp.sendgrid.net
25+
MAIL_PORT=587
26+
MAIL_USERNAME=sendgrid_username
27+
MAIL_PASSWORD=sendgrid_password
28+
MAIL_ENCRYPTION=tls
29+
MAIL_FROM_NAME="John Smith"
30+
MAIL_FROM_ADDRESS=[email protected]
31+
{% endcodeblock %}
32+
33+
{% info %}
34+
The `MAIL_FROM_NAME` field requires double quotes because there is a space in the string.
35+
{% endinfo %}
36+
37+
{% anchor h2 %}
38+
Creating a Mailable
39+
{% endanchor %}
40+
41+
Next you need to create a Mailable class, Laravel's CLI tool called Artisan makes that a simple feat.
42+
Open CLI, go to the project directory and type:
43+
44+
`php artisan make:mail TestEmail`
45+
46+
This command will create a new file under `app/Mail/TestEmail.php` and it should look something like this:
1547

1648
{% codeblock lang:php %}
1749
<?php
1850
19-
return array(
20-
'driver' => 'smtp',
21-
'host' => 'smtp.sendgrid.net',
22-
'port' => 587,
23-
'from' => array('address' => '[email protected]', 'name' => 'John Smith'),
24-
'encryption' => 'tls',
25-
'username' => 'sendgrid_username',
26-
'password' => 'sendgrid_password',
27-
);
28-
29-
?>
51+
namespace App\Mail;
52+
53+
use Illuminate\Bus\Queueable;
54+
use Illuminate\Mail\Mailable;
55+
use Illuminate\Queue\SerializesModels;
56+
use Illuminate\Contracts\Queue\ShouldQueue;
57+
58+
class TestEmail extends Mailable
59+
{
60+
use Queueable, SerializesModels;
61+
62+
public $data;
63+
64+
public function __construct($data)
65+
{
66+
$this->data = $data;
67+
}
68+
69+
public function build()
70+
{
71+
$address = '[email protected]';
72+
$subject = 'This is a demo!';
73+
$name = 'Jane Doe';
74+
75+
return $this->view('emails.test')
76+
->from($address, $name)
77+
->cc($address, $name)
78+
->bcc($address, $name)
79+
->replyTo($address, $name)
80+
->subject($subject)
81+
->with([ 'message' => $data['message'] ]);
82+
}
83+
}
3084
{% endcodeblock %}
3185

32-
You can use Laravel's Mail class just like you normally would, but all email will be sent through SendGrid!
86+
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:
87+
88+
{% codeblock lang:html %}
89+
<!DOCTYPE html>
90+
<html lang="en-US">
91+
<head>
92+
<meta charset="utf-8">
93+
</head>
94+
<body>
95+
<h2>Test Email</h2>
96+
<p>{{ $message }}</p>
97+
</body>
98+
</html>
99+
{% endcodeblock %}
100+
101+
{% anchor h2 %}
102+
Sending an email
103+
{% endanchor %}
104+
105+
Now that we have our Mailable Class created, all we need to do is run this code:
33106

34107
{% codeblock lang:php %}
35108
<?php
109+
use App\Mail\TestEmail;
36110
37-
Mail::send('emails.demo', $data, function($message)
38-
{
39-
$message->to('[email protected]', 'Jane Doe')->subject('This is a demo!');
40-
});
111+
$data = ['message' => 'This is a test!'];
41112

42-
?>
113+
Mail::to('[email protected]')->send(new TestEmail($data));
43114
{% endcodeblock %}
44115

45-
## Adding a category or custom field
116+
{% anchor h2 %}
117+
Adding a category or custom field
118+
{% endanchor %}
46119

47-
Categories in sendgrid allow you to split your statistics into categories. An example would be if you have a white labeled service you can split your statistics by the user login.
120+
Categories in SendGrid allow you to split your statistics into sections. For example, if you have a Whitelabeled service, you can split your statistics by the user login.
48121

49-
Another useful feature of sendgrid is the 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.
122+
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.
50123

124+
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:
51125

52126
{% codeblock lang:php %}
53127
<?php
54128
55-
Mail::send('emails.view', $data, function ($message)
56-
{
57-
$data['category'] = 'category';
58-
$data['unique_args']['variable_1'] = 'abc';
129+
namespace App\Mail;
59130
60-
$header = $this->asString($data);
131+
use Illuminate\Bus\Queueable;
132+
use Illuminate\Mail\Mailable;
133+
use Illuminate\Queue\SerializesModels;
134+
use Illuminate\Contracts\Queue\ShouldQueue;
61135
62-
$message->getSwiftMessage()->getHeaders()->addTextHeader('X-SMTPAPI', $header);
136+
class TestEmail extends Mailable
137+
{
138+
use Queueable, SerializesModels;
63139
64-
$message->to('[email protected]', 'Jane Doe')->subject('This is a demo!');
65-
});
140+
public $data;
66141
142+
public function __construct($data)
143+
{
144+
$this->data = $data;
145+
}
67146

68-
private function asJSON($data) // set as private with the expectation of being a class method
147+
public function build()
69148
{
70-
$json = json_encode($data);
149+
$address = '[email protected]';
150+
$subject = 'This is a demo!';
151+
$name = 'Jane Doe';
152+
153+
$headerData = [
154+
'category' => 'category',
155+
'unique_args' => [
156+
'variable_1' => 'abc'
157+
]
158+
];
159+
160+
$header = $this->asString($headerData);
161+
162+
$this->withSwiftMessage(function ($message) use ($header) {
163+
$message->getHeaders()
164+
->addTextHeader('X-SMTPAPI', $header);
165+
});
166+
167+
return $this->view('emails.test')
168+
->from($address, $name)
169+
->cc($address, $name)
170+
->bcc($address, $name)
171+
->replyTo($address, $name)
172+
->subject($subject)
173+
->with([ 'data' => $data ]);
174+
}
71175

176+
private function asJSON($data)
177+
{
178+
$json = json_encode($data);
72179
$json = preg_replace('/(["\]}])([,:])(["\[{])/', '$1$2 $3', $json);
73180

74181
return $json;
75182
}
76183

77-
private function asString($data) // set as private with the expectation of being a class method
184+
185+
private function asString($data)
78186
{
79187
$json = $this->asJSON($data);
80-
$str = wordwrap($json, 76, "\n ");
81-
82-
return $str;
188+
189+
return wordwrap($json, 76, "\n ");
83190
}
84-
?>
191+
}
85192
{% endcodeblock %}
86-

0 commit comments

Comments
 (0)