loading...

How to send Laravel mail using smtp

katheesh profile image Katheeskumar ・2 min read

Create Laravel project or if you are beginner in laravel to visit Laravel Docs

💥 Setup following variables in your .env file

MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=sample@example.com
MAIL_PASSWORD=************
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS=sample@yourdomain.com
MAIL_FROM_NAME="${APP_NAME}"

Don't use google gmail smtp details. because that is not a proper method to send emails and it is not working properly.

💥 Next you go to your project folder and open terminal run following command to create mail class

php artisan make:mail Mailer

💥 Now go to app/mail folder and setup your mail class like this one

<?php

namespace App\Mail;

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

class NewMail extends Mailable
{
    use Queueable, SerializesModels;

    public $details;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($details)
    {
        $this->details = $details;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->subject($this->details['subject'])
                    ->view('email.contact')
                    ->from($this->details['from'], $this->details['from']);
    }
}

💥 After configure mailing class create a view file with .blade.php extension

<h3 class="aligncenter" style="font-family: 'Helvetica Neue',Helvetica,Arial,'Lucida Grande',sans-serif; box-sizing: border-box; font-size: 20px; color: #000; line-height: 1.2em; font-weight: 400; text-align: center; margin: 40px 0 0;" align="center">{{ $details['title'] }}</h3>

Don't Forgot Mailing blade files only accept inline css's

💥 Finally set your controller on sending trigger process

public function new_mail(Request $request)
    {

        $details = [
            'to' => $request->to,
            'from' => $request->from,
            'subject' => $request->subject,
            'title' => $request->title,
            "body"  => $request->body
        ];

        \Mail::to($request->to)->send(new \App\Mail\NewMail($details));

        if (Mail::failures()) {
            return response()->json([
                'status'  => false,
                'data'    => $details,
                'message' => 'Nnot sending mail.. retry again...'
            ]);
        }
        return response()->json([
            'status'  => true,
            'data'    => $details,
            'message' => 'Your details mailed successfully'
        ]);
    }

If you want project source please visit my github profile and clone and refer it.

😍 Have a good day.

Discussion

pic
Editor guide