How to send an Email in Laravel

How to send an Email in Laravel

Hi !

Today we are going to learn how to send an email in laravel. Laravel is most widely used php framework. We will explore mail API of laravel and learn that how can we use laravel to send beautifully designed html emails. This tutorial can be extended to use multiple mail drivers as laravel supports a long range of email drivers.

Install Laravel

You can simply install laravel by using composer. Execute this command in terminal on your server root:

composer create-project --prefer-dist laravel/laravel laramailer

if you do not have composer installed globally you may download and install composer from https://getcomposer.org/ or download composer.phar file from https://getcomposer.org/ and run below command:

php composer.phar create-project --prefer-dist laravel/laravel laramailer

if you are using lampp on linux then use below command:

/opt/lampp/bin/php composer.phar create-project --prefer-dist laravel/laravel laramailer

Running above command will create laramailer directory in which laravel will be installed.

Laravel implements swift mailer library which makes it easy to manage email. Default mail settings are available in laramailer/config/mail.php

Let’s proceed with adding the e-mail sending functionality to our laravel application. Run below command in terminal. Open your terminal inside laramailer and run below command. Remember if you are using lampp and php is not globally installed use /opt/lampp/bin/php instead of php.

Run below command in terminal:

php artisan make:mail LaraEmail

Running this command will create a file named LaraEmail.php in app/Mail directory. Generated file will have some pre-generated code and we will add some code to the generated file. Final file will be like this:

<?php

namespace App\Mail;

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

class LaraEmail extends Mailable
{
    use Queueable, SerializesModels;

    protected $mailData;

    
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($mailData)
    {

        $this->mailData = $mailData;
        //
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        $address = $this->mailData->to;
        $subject = $this->mailData->subject;
        $name = $this->mailData->name;
        $cc = $this->mailData->cc;
        $bcc = $this->mailData->bcc;
        $from = $this->mailData->from;

        return $this->view('email.laraemail')
            ->text('email.laraemail_plain')
            ->from($from, $name)
            ->cc($address, $name)
            ->bcc($cc, $name)
            ->replyTo($from, $name)
            ->subject($subject)
            ->with(['mailMessage' => $this->mailData]);;
        
    }
}

The above code is very easy and can be understood easily. But still let’s see the code of build function.

We have passed the mailData object to laraEmail class , this objects contains all the information that is need to send the email. mailData object contains to email address, subject and other information. We pass all these data to view using with() method , mailMessage variable will be accessible in the email view file. Basically build method initializes the email specific values like to email address, template file for email etc. Now let’s create files which holds the html view of email.

Create 2 files in path “resources/views/email” named as “laraemail.blade.php” and “laraemail_plain.blade.php”. laraemail.blade.php will contain the HTML code and laraemail_plain.blade.php will hold the code for plain view of email.

Let’s define the content of laraemail.blade.php

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <meta charset="utf-8"><title>{{$mailMessage->title}}</title>
    </head>
    <body>
        Dear {{$mailMessage->recieverName}} !
        <p>Thank You for contacting us. We will revert back on your query 
with in 24 Hours.</p>
<p></p>
Thank You,
<br/>
{{ $mailMessage->sender }}
<br/>
{{ $mailMessage->senderCompany}}
    </body>
</html>

Now let’s create the plain version of same email in file laraemail_plain.blade.php

Dear {{$mailMessage->recieverName}} !
Thank You for contacting us. We will revert back on your query 
with in 24 Hours.
Thank You,
{{ $mailMessage->sender }}
{{ $mailMessage->senderCompany}}

Now let’s write the controller to send Email. Run below command to generate the controller using artisan or you may also create the controller file by yourself. Let’s run the command:

 php artisan make:controller EmailController

Now let’s create sendEmail Action which will send the email. Final Controller code looks like below:

namespace App\Http\Controllers;
 
use App\Http\Controllers\Controller;
use App\Mail\LaraEmail;
use Illuminate\Support\Facades\Mail;
 
class EmailController extends Controller
{
    public function sendEmail()
    {
        $mailInfo = new \stdClass();
        $mailInfo->recieverName = "John Defoe";
        $mailInfo->sender = "Mike";
        $mailInfo->senderCompany = "CodeInnovers Technologies";
        $mailInfo->to = "[email protected]";
        $mailInfo->subject = "Support- Team CodeInnovers";
        $mailInfo->name = "Mike";
        $mailInfo->cc = "[email protected]";
        $mailInfo->bcc = "[email protected]";
 
        Mail::to("[email protected]")
           ->send(new LaraEmail($mailInfo));
    }
}

Above code will send an email to the entered email. We can easily dynamic our code, but now we should test this code and for this we need to make a request to our controller. TO do this we will add below code to our web.php file. web.php file can be located inside routes folder.

Route::get('laramail/send', '[email protected]');

We are adding the route for get request. Whenever a request is sent <domain>/public/laramail/send address laravel routing will forward the request to our EmailController’s sendEmail action.

Hit the above URL in your browser , and laravel will send the email. Laravel also provides a feature where you may log your emails to log file.

To use this feature open config/mail.php set your MAIL_DRIVER value to log and hit the URL again. This time your email message will be logged to “storage/logs/laravel.log”.

You may drop me a message or write down in comment if you face any issue and i will be happy to assist you.

Add a Comment

Your email address will not be published.