1
Write a post

Automating Mails In Your Laravel Applications

Published Jun 27, 2017

In this tutorial, I will be teaching on how to automate mails in your Laravel Application. This is what I mean. The User may sign up on your platform and you may want to appreciate the user for signing up on the platform. For the purpose of this tutorial, I will be building be building an application that allows the user to sign up for newsletter and then automate mails for appreciating any user that signs up for the newsletter. I will be teaching you two (2) different ways of automating mails. Enjoy as you learn!!!

Requirement

  • PHP ( > 5.6.9)
  • Mysql
  • Laravel
  • MailTrap

Create Controller

First, start by creating a controller for the Newsletter Application using the command below:

php artisan make:controller NewsLetterController --resource

Once the controller is created, delete every other method in the controller apart from the create and store method then add this to the create method in the NewsLetterController class

return view('news-letter-view');

After doing the above, you should have something like this in your controller file

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class NewsLetterController extends Controller
{
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('news-letter-view');
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }
    
}

Creating the View

We have to create a view where the user can sign up for the newsletter and so we will do that by going to the views folder in the resources folder of our Laravel Application and then create a file named
news-letter-view.blade.php then add the following codes into the file.

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>NewsLetter Application | Automating Mails</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-4">
            <hr>
            <div class="header text-center">
                <span>Apply to receive our Newsletter via Email</span>
            </div>
            <br>
            @if (session('alert'))
                <p class="alert alert-success">{{ session('alert') }}</p>
            @endif
            @if (count($errors) > 0)
                @foreach ($errors->all() as $error)
                        <p class="text-center alert alert-danger">{{ $error }}</p>
                @endforeach
            @endif
            <form action="{{ url('apply') }}" method="post" class="form-inline">
                {{ csrf_field() }}
                <div class="form-group">
                    <label for="email">Email</label>
                    <input type="email" name="email" class="form-control" placeholder="jane.test@example.com">
                </div>
                <button type="submit" class="btn btn-primary">Apply</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>

Once you have this let us create our model and migration for the application.

Creating Model and Migration

We want to be able to save the email of the user in our database that is why we are creating model and migration. But before you continue this tutorial, make sure you have your database configuration right especially in your .env file or you will encounter issues. For the purpose of this tutorial, we are using Mysql

Run this in your terminal to create both the model file and migration file at the same time.

php artisan make:model NewsLetter -m  

Once they have been created, add this to your NewsLetter.php file in App folder

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class NewsLetter extends Model
{
    protected $fillable=['email'];
}

then, in your migration file, add this:

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateNewsLettersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('news_letters', function (Blueprint $table) {
            $table->increments('id');
            $table->string('email');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('news_letters');
    }
}

After doing the above, run migration with this command in your terminal:

php artisan migrate

Once that is successful, we have to handle the form in our controller

Handling the form-control

To handle the form in our controller, make sure your controller file looks like the one below.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\NewsLetter;
use Validator;
class NewsLetterController extends Controller
{
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('news-letter-view');
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'email'=>'required|distinct'
        ]);
        $newsletter = new NewsLetter();
        $newsletter->email = $request->input('email');
        if ($newsletter->save())
        {
            return redirect()->back()->with('alert','You have successfully applied for our Newsletter');
        }else{
            return redirect()->back()->withErrors($validator);
        }
    }
}


Adding Routes and Doing the first test

I know you are eager to see the application. For you to see the application work, add this to your web.php file in the routes folder of your application.

Route::get('newsletter',[
    'uses'=>'NewsLetterController@create',
    'as'=>'newsletter'
]);
Route::post('apply',[
    'uses'=>'NewsLetterController@store',
    'as'=>'apply'
]);

Go to your terminal and launch your application on the browser with this command

php artisan serve --port=8000

Then, you can go to http://127.0.0.1:8000/newsletter to see your application view and then test the form. You should see something like this.

Working on Automating Emails

As our main focus, we have to automate the email once the user applies for the newsletter. We will be working with Mailtrap in this tutorial.

  • Create an account on Mailtrap
  • update your .env file with your Mailtrap credentials
MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=6034b54b9e5c9f
MAIL_PASSWORD=df264279bf16ac
MAIL_ENCRYPTION=tls

Disclaimer: Get your credentials from your mailtrap MAIL_USERNAME and MAIL_PASSWORD from your account. The ones above are incorrect.

Creating a simple Email Template

Go to viewsfolder in theresourcesfolder of our Laravel Application and then create a folder calledemailsthen create a file inside it calledsuccess.blade.php` then add this into the file.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>Hello,</p>
<p>
    Thanks for signing up for our newsletter.
    I am sure this is your email <span>{{ $email }}</span><br>
    We love you!!!
</p>
<p>
    Goodness Kayode | Pusher of Codes
    <br>
    CodebagNG
</p>
</body>
</html>

Update your Controller to handle Automatic Mails (First Approach)

This is the first approach to automating emails in your Laravel Application. If you don’t want this method, you can got with the second method below.
Make sure your Controller looks this this:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\NewsLetter;
use Illuminate\Support\Facades\Mail;
use Validator;
class NewsLetterController extends Controller
{
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('news-letter-view');
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'email'=>'required|distinct'
        ]);
        $newsletter = new NewsLetter();
        $newsletter->email = $request->input('email');
        if ($newsletter->save())
        {
            Mail::send('emails.success', ['email' => $newsletter->email], function ($message)
            {
                $message->from('gtkbrain@gmail.com', 'Goodness Kayode');
                $message->to('gtkbrain@yahoo.com');
            });
            return redirect()->back()->with('alert','You have successfully applied for our Newsletter');
        }else{
            return redirect()->back()->withErrors($validator);
        }
    }
}


Working With Mailables (Second Approach)

  • Create a mailable class by running the command below in your terminal
    php artisan make:mail Success

  • Go to app/Mail folder, you would see Success.php file there. Update to make it look like the below

<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\NewsLetter;
class Success extends Mailable
{
    use Queueable, SerializesModels;
    /**
     * The order instance.
     *
     * @var Order
     */
    public $newsletter;
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct(NewsLetter $newsLetter)
    {
        $this->newsletter = $newsLetter;
    }
    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('emails.success')->with([
            'email'=> $this->newsletter->email
        ]);
    }
}
  • Update your controller to look like this
<?php
namespace App\Http\Controllers;
use App\Mail\Success;
use Illuminate\Http\Request;
use App\NewsLetter;
use Illuminate\Support\Facades\Mail;
use Validator;
class NewsLetterController extends Controller
{
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('news-letter-view');
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'email'=>'required|distinct'
        ]);
        $newsletter = new NewsLetter();
        $newsletter->email = $request->input('email');
        if ($newsletter->save())
        {
            Mail::send('emails.success', ['email' => $newsletter->email], function ($message)
            {
                $message->from('gtkbrain@gmail.com', 'Goodness Kayode');
                $message->to('gtkbrain@yahoo.com');
            });
            return redirect()->back()->with('alert','You have successfully applied for our Newsletter');
        }else{
            return redirect()->back()->withErrors($validator);
        }
    }
    public function autoMail(Request $request)
    {
        $this->validate($request, [
            'email'=>'required|distinct'
        ]);
        $newsletter = new NewsLetter();
        $newsletter->email = $request->input('email');
         if ($newsletter->save())
        {
            Mail::to($newsletter->email)->send(new Success($newsletter));
            return redirect()->back()->with('alert','You have successfully applied for our Newsletter');
        }else{
            return redirect()->back()->withErrors($validator);
        }
    }
}
  • Add this to your routes/web.php file
Route::post('apply-two',[
    'uses'=>'NewsLetterController@autoMail',
    'as'=>'apply-two'
]);
  • Update your resources/views/news-letter-view.blade.php file to look like this:
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>NewsLetter Application | Automating Mails</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-4">
            <hr>
            <div class="header text-center">
                <span>Apply to receive our Newsletter via Email</span>
            </div>
            <br>
            @if (session('alert'))
                <p class="alert alert-success">{{ session('alert') }}</p>
            @endif
            @if (count($errors) > 0)
                @foreach ($errors->all() as $error)
                        <p class="text-center alert alert-danger">{{ $error }}</p>
                @endforeach
            @endif
            <form action="{{ url('apply-two') }}" method="post" class="form-inline">
                {{ csrf_field() }}
                <div class="form-group">
                    <label for="email">Email</label>
                    <input type="email" name="email" class="form-control" placeholder="jane.test@example.com">
                </div>
                <button type="submit" class="btn btn-primary">Apply</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>

Fire Up Your Application

Irrespective of the approach you used in this tutorial, go to your terminal and launch your application on the browser with this command

php artisan serve --port=8000

Then, you can go to http://127.0.0.1:8000/newsletter to see your application view and then fill the form. You should see something like this.

Hurray!!! It Works

Once you carry out everything I asked you to carry out in this tutorial, you should be able to see something like this in your Mailtrap inbox.

How can you thank me?

I will appreciate comments, tweets and posts on Scotch, twitter or Hackernews.
You can appreciate me by following me on Github , twitter and subscribe to my Youtube Channel!

Discover and read more posts from Goodness Toluwanimi Kayode
get started
Enjoy this post?

Leave a like and comment for Goodness

2
Be the first to share your opinion

Get curated posts in your inbox

Learn programming by reading more posts like this