How To Use Laravel Mailtrap To Send Email?

9
414
Using Mailtrap To Send Email

Sending mails in a different account (user emails) for testing in the local server is a headache. Every time you need to send an email through the same email or ask a colleague to check an email. Today you are going to learn laravel mailtrap to get rid of this. You can send mail into any email address and receive into mailtrap inbox. So, lets get started.

# Requirements

  • Laravel installed in your system. Click Here to know how to install Laravel Framework.
  • Mailtrap account. You can create it here.

# Setting Up Laravel Mailtrap

After logging in into mailtrap account you will get smtp credentials from dashboard.

Now open your .env file situated in root folder in your project.

/* .env */    

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your-username
MAIL_PASSWORD=your-password
MAIL_ENCRYPTION=null

Mailtrap setup is completed. Now every time you send an email on any address, you will get an email into your mailtrap inbox. Let’s take an example.

# Prerequisite

I’m using simple laravel mailable class to send an email. This is not an email sending tutorial, That’s why I’m doing it simply.

Update welcome.blade.php to create simple email input.

/* resources > views > welcome.blade.php */

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Laravel Mailtrap</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>

<div class="container my-5 align-center">

    @if(session()->has('msg'))
    <div class="alert alert-info">
        {{ session()->get('msg') }}
    </div>
    @endif

    <form action="{{ route('send.email') }}" method="post">
        {{ csrf_field() }}
        <div class="form-group">
            <label>Email Address</label>
            <input type="email" class="form-control" name="email" required>
        </div>
        <div class="form-group">
            <button type="submit" class="btn btn-primary">Send</button>
        </div>
    </form>
</div>

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>

Create a mailable class with the following command and replace the following code. I have added email from, subject statically.

php artisan make:mail WelcomeMail
/* app > Mail > WelcomeMail.php  */

<?php

namespace App\Mail;

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

class WelcomeMail extends Mailable
{
    use Queueable, SerializesModels;

    protected $email;

    public function __construct($email)
    {
        $this->email = $email;
    }

    public function build()
    {
        return $this->from("admin@test.com")->subject('Welcome Mail')->view('emails.welcome')->with(['email' => $this->email]);
    }
}

For email body, create email page template in recources > views > emails > welcome.blade.php

/* recources > views > emails > welcome.blade.php */

<p>Welcome, <b>{{ $email }}</b></p>

Finally, update routes and controller to submit input to send email.

/* routes > web.php */

<?php

Route::get('/', 'WelcomeController@index');
Route::post('send/email', 'WelcomeController@sendEmail')->name('send.email');
/* app > Http > Controllers > WelcomeController.php */

<?php

namespace App\Http\Controllers;

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

class WelcomeController extends Controller
{
    public function index()
    {
        return view('welcome');
    }

    public function sendEmail(Request $request)
    {
        Mail::to($request->email)->send(new WelcomeMail($request->email));
        return redirect()->back()->with(['msg' => 'Email sent successfully']);
    }
}

Start PHP development server with the following command.

php artisan serve

This will start server at locahost:8000. That’s it. Check mailtrap inbox after submitting form.

Learn more about Laravel Framework

Previous articleHow To Use Laravel Validation
Next articleHow To Send Mail Using Queue In Laravel?
Welcome to the world of web development, where technology and creativity come together to bring ideas to life. My name is Keyur Gadher, and as a web development blogger, I am here to share my knowledge and experience with you. From front-end web development to back-end programming, I will provide you with valuable tips, tricks, and techniques to help you create beautiful and functional websites that are tailored to your specific needs. Whether you're a beginner or a seasoned pro, I am here to help you take your web development skills to the next level. Join me today and let's start coding!

9 COMMENTS

  1. hi!,I love your writing very a lot! proportion we keep up a correspondence extra approximately your article on AOL? I require an expert in this space to unravel my problem. Maybe that’s you! Looking forward to see you.

  2. Aw, this was a really nice post. In concept I wish to put in writing like this moreover ?taking time and precise effort to make an excellent article?but what can I say?I procrastinate alot and certainly not appear to get one thing done.

  3. A powerful share, I simply given this onto a colleague who was doing a little evaluation on this. And he the truth is bought me breakfast as a result of I found it for him.. smile. So let me reword that: Thnx for the treat! However yeah Thnkx for spending the time to debate this, I feel strongly about it and love reading more on this topic. If potential, as you turn out to be experience, would you thoughts updating your weblog with extra details? It is extremely helpful for me. Massive thumb up for this weblog submit!

  4. I think this is among the so much important information for me. And i’m glad studying your article. However wanna statement on some common issues, The web site style is ideal, the articles is in point of fact excellent : D. Just right process, cheers

LEAVE A REPLY

Please enter your comment!
Please enter your name here