How Can We Help?
Laravel
Laravel provides a complete API over the famous SwiftMailer library with drivers for SMTP, PHP’s mail, sendmail and more. For this example, we’ll be sending an email with Mail250 using the SMTP Driver. For more information, check out the docs for Laravel’s Mail interface.
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
Check your .env file and configure these variables:
MAIL_DRIVER=smtp
MAIL_HOST=smtp.swipemail.in
MAIL_PORT=587
MAIL_USERNAME=mail250_username
MAIL_PASSWORD=mail250_password
MAIL_ENCRYPTION=tls
MAIL_FROM_NAME="John Smith"
[email protected]
The `MAIL_FROM_NAME` field requires double quotes because there is a space in the string.
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.
Creating a Mailable
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:
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class TestEmail extends Mailable
{
use Queueable, SerializesModels;
public $data;
public function __construct($data)
{
$this->data = $data;
}
public function build()
{
$address = '[email protected]';
$subject = 'This is a demo!';
$name = 'Jane Doe';
return $this->view('emails.test')
->from($address, $name)
->cc($address, $name)
->bcc($address, $name)
->replyTo($address, $name)
->subject($subject)
->with([ 'message' => $this->data['message'] ]);
}
}
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:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
</head>
<body>
<h2>Test Email</h2>
<p>{{ $message }}</p>
</body>
</html>
Sending an email
Now that we have our Mailable Class created, all we need to do is run this code:
<?php
use App\Mail\TestEmail;
$data = ['message' => 'This is a test!'];
Mail::to('[email protected]')->send(new TestEmail($data));