Laravel - Sending Emails

Another important feature of Laravel is providing clean and simple API use, which is free and rich in library features - "SwiftMailer," which is used for sending emails. With the help of its library functions, Laravel developers find it easy to send emails without any hurdles. Developers can use blade syntax to inject data within a template because email templates are loaded in the same way as views.

The syntax looks something like this:

Syntax:
void send(string|array $view, array $data, Closure|string $callback)

Here void indicates that this will not return any value, string|array $view provides the view name which is having the email message. $data(array) is the set of data that has to be passed to view. $callback holds the capability to customize recipients' subject and other mail details as a closure callback that gets received as message instance.

Different Methods of Mailing System

The third argument in the above function takes the instance of message and there are some following functions which helps performing the mailing interaction better. These are:

  • $message -> subject('Laravel Tutorial');
  • $message ->from('testuser@example.com', 'anyname');
  • $message ->to('alex@example.com', 'Alex');

Other commonly used methods are:

  • $message ->sender('testuser@example.com', 'anyname');
  • $message ->returnPath('testuser@example.com');
  • $message ->cc('testuser@example.com', 'anyname');
  • $message ->bcc('neha@example.com', 'Neha');
  • $message ->replyTo('testuser@example.com', 'anyname');
  • $message ->priority(4);

For sending plain text mail, you have to use the syntax shown below:

Mail::send(['text'=>'text.view'], $data, $callback);

This entire syntax is in the form of an array-key-value format, where the first argument took in the form of the array followed by text and name-of-view as key-value pair.

Steps to Send Email in Laravel

So the theme is to send an email via Gmail account and need the Laravel environment file, which is .env file to configure with your Gmail account. The environment file contains the script:

MAIL_DRIVER = smtp
MAIL_HOST = smtp.gmail.com
MAIL_PORT = 587
MAIL_USERNAME = developers-Gmail-username
MAIL_PASSWORD = developers-password
MAIL_ENCRYPTION = tls

Next, you have to clear the cache and restart your Laravel server. For that, you have to use the following commands:

php artisan config:cache

Then for creating MailController, you have to type and run the command given below:

php artisan make:controller MailController --plain

Then you have to setup the inside content of the MailController.php file, and for this, you have to write the script mentioned below:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Mail;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class SendMailController extends Controller
{
    public function txt_mail()
    {
        $info = array(
            'name' => "Alex"
        );
        Mail::send(['text' => 'mail'], $info, function ($message)
        {
            $message->to('alex@example.com', 'W3SCHOOLS')
                ->subject('Basic test eMail from W3schools.');
            $message->from('sender@example.com', 'Alex');
        });
        echo "Successfully sent the email";
    }

    public function html_mail()
    {
        $info = array(
            'name' => "Alex"
        );
        Mail::send('mail', $info, function ($message)
        {
            $message->to('alex@example.com', 'w3schools')
                ->subject('HTML test eMail from W3schools.');
            $message->from('karlosray@gmail.com', 'Alex');
        });
        echo "Successfully sent the email";
    }

    public function attached_mail()
    {
        $info = array(
            'name' => "Alex"
        );
        Mail::send('mail', $info, function ($message)
        {
            $message->to('alex@example.com', 'w3schools')
                ->subject('Test eMail with an attachment from W3schools.');
            $message->attach('D:\laravel_main\laravel\public\uploads\pic.jpg');
            $message->attach('D:\laravel_main\laravel\public\uploads\message_mail.txt');
            $message->from('karlosray@gmail.com', 'Alex');
        });
        echo "Successfully sent the email";
    }
}

In this file location resources/views/mail.blade.php, you have to type the below-mentioned command:

<h1> Hello, {{ $name }} </h1>

<p> Laravel MAIL System </p>

Also, add the script in routes.php files with the following commands:

Route::get('sendtxtmail','MailController@txt_mail');
Route::get('sendhtmlmail','MailController@html_mail');
Route::get('sendattachedemail','MailController@attached_email');

For testing the setup and output, type the following URLs:

  1. http://localhost:8000/sendtxtmail
  2. http://localhost:8000/sendhtmlmail
  3. http://localhost:8000/sendattachedmail

Scroll Back to Top