How To Send Email Using Laravel Mail

thumbnail

Hi guys, welcome back to https://codingofcents.com. Today we will discuss how to send emails from with laravel.

We can easily send email using Laravel because it provides Mail class that supports many drivers.

Before beginning this tutorial make sure you have installed fresh laravel application.

Change .env file

In your laravel application, edit .env file and update the email variable. You can add your own Cpanel email or you can use Gmail for testing.

In this example, we will use SMTP as a driver to send emails.

MAIL_DRIVER=smtp
MAIL_HOST=YOURHOST
MAIL_PORT=587
MAIL_USERNAME=USERNAME
MAIL_PASSWORD=PASSWORD
MAIL_ENCRYPTION=null

Or if you want to use your google account, go to your less secure setting: https://myaccount.google.com/lesssecureapps and turn on Allow Less Secure apps

How To Send Email Using Laravel Mail
How To Send Email Using Laravel Mail

Then change the .env like bellow

MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=465
MAIL_USERNAME=ENTER_YOUR_GMAIL_USERNAME
MAIL_PASSWORD=ENTER_YOUR_GMAIL_PASSWORD
MAIL_ENCRYPTION=ssl

Mail Class

Next, create a Mail class with PHP artisan command.

php artisan make:mail SendInvoice

The command will create SendInvoice.php under the app/Mail folder. In this example, we will send an invoice to the customer. Edit SendInvoice class so look like bellow.

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendInvoice extends Mailable
{
    use Queueable, SerializesModels;
    public $subject;
    public $content;
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($subject, $content)
    {
        $this->subject = $subject;
        $this->content = $content;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->markdown('mails.sendInvoice')
                ->from('[email protected]')
                ->subject($this->subject)
                ->with('content', $this->content);
    }
}

After that, create an email template that used to display our email content.

Create sendInvoice.blade.php in resources/views/mail folder and edit like bellow.

@component('mail::message')

<div style="display: inline">
  <div style="text-align: left;">
    {{ $content["CompanyName"] }}
  </div>
  <div style="text-align: right;">
    {{ $content["InvDate"] }} 

    Invoice for {{ '# '.$content["InvNo"] }}
  </div>
</div>
<br/>
{{ $content["CompanyAddress"] }}
<br/>

##### Item Details
<hr>
@component('mail::table')

  | Item       | Quantity      | Price     |
  | :------------ |:-------------| :-------------|
  @foreach ($content["Details"] as $itm)
    | {{ $itm["Item"] }} | {{ $itm["Qty"] }} | {{ number_format($itm["Price"],2) }} | 
  @endforeach
@endcomponent
<br/>

##### Payment Details
<hr>
@component('mail::table')

  | Item       | Total      |
  | :------------ |:-------------|
  @foreach ($content["Payment"] as $itm)
    | {{ $itm["Item"] }} | {{ number_format($itm["Total"], 2) }} |
  @endforeach
@endcomponent
<br/>

Thanks,<br>
{{ config('app.name') }}
@endcomponent

Email Controller

Next, for the logic of our email, create email controller

php artisan make:controller InvoiceController

Inside this controller we create one method sendEmail, this method will call sendInvoice class with subject and content as parameters.

Parameter $content is an array that includes all data that we need in the email content.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Mail\SendInvoice;
use Illuminate\Support\Facades\Mail;

class InvoiceController extends Controller
{
    public function sendEmail()
    {
		$content = [
    		"CompanyName" => "Codingofcents",
    		"InvDate" => date("m/d/Y", strtotime(date("Y-m-d"))),
    		"InvNo" => "8910",
    		"CompanyAddress" => "Luwuk, Central Sulawesi, Indonesia",
    		"Details" => [
    			["Item" => "13 inch Macbook Pro", "Qty" =>  2, "Price" => 1299],
    			["Item" => "15 inch Macbook Pro", "Qty" =>  1, "Price" => 2399],
    		],
    		"Payment" => [
    			["Item" => "Total Tax", "Total" => 0],
    			["Item" => "Subtotal Price", "Total" => 4997],
    			["Item" => "Total Price", "Total" => 4997],
    		]
    	];

    	$subjects = "Invoice #8910";
    	$to = "[email protected]";
    	
    	Mail::to($to)->send(new SendInvoice($subjects, $content));
    	try {

    		return response()->json("Email Sent!");
    	} catch (\Exception $e) {
    		return response()->json($e->getMessage());
    	}
    }
}

Edit Route

Next after creating the logic, we need to call the controller on the route so we can send the email. Add a line in route and add this code

Route::get("email", "[email protected]");

Conclusion

Laravel provides us, mail class, therefore we can send an email out of the box.

Sponsored Links
Hi, my name is I Wayan Tisna Adi Muliarta. You can call me Tisna. I am the author of the Coding Of Cents

Leave a Reply

Your email address will not be published. Required fields are marked *

5 × two =

Back To Top