Send Mail using Laravel 5.4 + VueJS

Gửi mail là một trong những tính năng mà các website kinh doanh nào cũng có , giúp cho việc gửi thông tin các sản phẩm khi mua hàng trên website , thông báo cho người dùng biết được về những sản phẩm mà họ đã mua. 

Hôm nay minh sẽ chia sẻ với các bạn cách tích hợp tính năng gửi mail trong Laravel 5.4 kết hợp với Vuejs, để xây dụng nhé, bên cạnh đó mình cũng sẵn giới thiệu cho các bạn biết Vuejs, Hiện này Laravel kết hợp với Vuejs rất nhiều, vì rất dễ để cài đặt và tích hợp sử dụng, các bạn có thể xem lại bài viết Create Template Laravel 5.4 + Vuejs

Đầu tinh bạn cần download project về:composer create-project --prefer-dist laravel/laravel create-laravel-vuejs "5.4.*" 

Sau khi download về bạn gõ câu lệnh cài bộ thư viện của laravel như sau: npm install

Tiếp tục bạn cần cài đặt bộ thư viện của Vuejs tích hợp vô Laravel với câu lệnh thật đơn giản như sau:

npm install --save-dev vue-axios vue-loader vue-router vue-template-compiler 

* Phần xây dựng FrontEnd

Bạn vào đường dẫn C:\xampp\htdocs\create-laravel-vuejs\resources\views và tạo cho mình 2 thư mục đó là(layouts,pages)

+ Trong thư mục views/layouts: tạo file main.blade.php (dùng cầu hình template chính) các bạn chú ý tới cái <div id="app"></div> nhé, cái này dùng khai báo khi Vuejs render template ra 

<!doctype html>
<html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8">
        <meta https-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
 
        <title>Laravel Vuejs</title>
        <!-- Fonts -->
        <meta name="csrf-token" content="{{ csrf_token() }}">
      <link rel="stylesheet" type="text/css" href="{{ mix('css/app.css') }}">
    </head>
    <body>
        <div id="app">
            
        </div>
    </body>
    <script type="text/javascript" src="{{ mix('js/app.js') }}"></script>
</html>

+ Trong thư mục views/pages: Bạn tạo cho mình với các file như sau(email.blade.php,success.blade.php,infomation.blade.php)

File email.blade.php: các bạn chú ý tới <FormMail></FormMail> dùng render ra cái form hiện cho người dùng gõ

@extends('layouts.main')

@section('content')
		<div class="row">
				<div class="col-md-12">
					<FormMail></FormMail>
				</div>
		</div>
@endsection

File success.balde.php: file này dùng để thông báo thông tin mình đã gửi mail thành công, các bạn cũng chú ý tới <SuccessMail></SuccessMail> , chổ này Vuejs sẽ render template ra

@extends('layouts.main')
@section('content')
	<div class="row">
		<SuccessMail></SuccessMail>
	</div>
@endsection

File infomation.blade.php:file này dùng để khi chúng ta gửi mail kèm theo giao diện mà chúng ta muốn bên người nhận nhìn thấy, giống thư thông kê sản phẩm và giá mà khác đã mua hàng

<h1>Hello! </h1>
<p>{{$demo->email}}</p>
<p>{{$demo->bodycontent}}</p>

Tiếp theo bạn vào đường dần sau:C:\xampp\htdocs\create-laravel-vuejs\resources\assets\js và tạo cho mình một số file như sau:

+ Tại thư mục assets/js/components: tạo file template (FormMail.vue,SuccessMail.vue)

File FormMail.vue: là file giao diện form chúng ta cần thiết kế cho người dùng gõ, các bạn chú ý tới phần script trong file source bên dưới. Có hàm onSubmit dùng để gửi thông tin về Laravel nhận dữ liệu người dụng nhập

<template>
    <div class="container">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <div class="panel panel-default">
                    <div class="panel-heading">{{title}}</div>
                    <div class="panel-body">
                        <form action="" method="post" v-on:submit.prevent="onSubmit">

                             <div class="form-group">
                                <label for="email">Email address</label>
                                <input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email" v-model="info.email">
                              </div>
                              <div class="form-group">
                                <label for="content">Body content</label>
                                <textarea type="password" class="form-control" id="bodycontent" placeholder="Body content" v-model="info.bodycontent" ></textarea>
                              </div>
                             
                              <button type="submit" class="btn btn-primary">Send mail</button>
                             
                        </form>
                        <!--  <button class="btn btn-primary" v-on:click="thongtin()">Send mail</button> -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
       data(){
          return{
            title:'Form Mail',
            info:{},
            success:false
          }
       },
       methods:{
            onSubmit(){
                this.axios.post('http://localhost:8000/email/form',
                    {email:this.info.email,bodycontent:this.info.bodycontent})
                  .then(response => {
                    console.log(response);
                      this.success = response.data.success;
                      if(this.success){
                        this.$router.push({name:'SuccessMail',
                            params:{
                                success:this.success,
                                email:this.info.email,
                                bodycontent:this.info.bodycontent
                            }
                        });
                      }
                  })
                  .catch(error => {
                    console.log(error)
                    this.success = false
                  });
                  
            }


       }
    }
</script>

File SuccessMail.vue: dùng gửi thông tin thông báo là gửi thành công, bạn cần xem cái đoạn script nhận thông tin bên dưới nhé

<template>
	<div class="row">
		<div class="col-md-18" v-if="success">
			<h2>{{title}}</h2>
			<label>Email:{{email}}</label>
			<p>{{bodycontent}}</p>
		</div>
		

	</div>
</template>
<script>
	export default {
		data(){
			return{
				success:this.$route.params.success,
				title:'Send mail successfuly',
				email:this.$route.params.email,
				bodycontent:this.$route.params.email
			}
		}
	}

</script>

Tiếp theo chúng ta ra trỏ lại thư mục C:\xampp\htdocs\create-laravel-vuejs\resources\assets\js và tạo cho mình một số file như sao (App.vue,routers.js

 File App.vue: 

<template>
    <div class="container">
        <div>
            <transition name="fade">
                <router-view></router-view>
            </transition>
        </div>
    </div>
</template>
 
<style>
    .fade-enter-active, .fade-leave-active {
      transition: opacity .5s
    }
    .fade-enter, .fade-leave-active {
      opacity: 0
    }
</style>
 
<script>
 
    export default{
    }

File router.js: dùng import các Component vào đây dễ quản lý điều hướng nhé


import FormMail from './components/FormMail.vue';
import SuccessMail from './components/SuccessMail';
export default  [
  {
      name: 'FormMail',
      path: '/email/form',
      component: FormMail
  },
  {
  	  name:'SuccessMail',
  	  path:'/email/success',
  	  component: SuccessMail
  }
 
];

Tiếp theo bạn mở file app.js cung trhong thư mục trên và sửa lại như sau:

import Vue from 'Vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
 
import VueAxios from 'vue-axios';
import axios from 'axios';
Vue.use(VueAxios,axios);
import App from './App.vue';
import outroutes from './routers';

const router = new VueRouter({mode:'history', routes: outroutes});
new Vue(Vue.util.extend({router},App)).$mount('#app');

Vậy là chúng ta xong phần FrontEnd, nếu các bạn không hiểu có thể xem lại mấy bài kết hợp Laravel + Vuejs của mình đã chia sẻ lúc trước nhé!

* Xây dụng BackEnd

Bạn mở cmd lên và chạy câu lệnh tạo Controller trong laravel nhé, ở đây mình tao sẵn rồi tên là EmailController, Tiếp tục bạn chạy câu lệnh tạo một cái mail trong laravel đã hổ trợ cú pháp cho ta sẵn như sau:

php artisan make:mail SendMailable

ở trên mình tạo một file mail tên là SendMailable, giờ chúng ta đi vô từng file nào:

Bạn mởi file EmailController lên và chỉnh lại như sau:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use App\Mail\SendMailable;
use Mail;
class EmailController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return response()->json(['success'=>1]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $email = $request->email;
        $bodycontent = $request->bodycontent;
        $objDemo = new \stdClass();
        $objDemo->email =  $email;
        $objDemo->bodycontent =  $bodycontent;
        Mail::to("thanhhoacth2013@gmail.com")->send(new SendMailable($objDemo));

        return response()->json(['success'=>true,'email'=>$email,'bodycontent'=>$bodycontent]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

Tiếp theo bạn mở file SendMailable trong thư mục C:\xampp\htdocs\create-laravel-vuejs\app\Mail này và sửa lại như sau:

<?php

namespace App\Mail;

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

class SendMailable extends Mailable
{
    use Queueable, SerializesModels;
    public $demo;

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

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        // return $this->from('nguyenthanhhoa.com@gmail.com')
        //         ->view('name')->with('name', "gui thanh cong");

        return $this->from('nguyenthanhhoa.com@gmail.com')
                    ->view('pages.infomation')
                    ->text('pages.success')
                    ->with(
                      [
                            'message' => 'Ban co the kiem tra email',
                      ])
                    ->attach(public_path('/images').'/logo33.png', [
                              'as' => 'logo33.png',
                              'mime' => 'image/jpeg',
                      ]);
                    
    }
}

Tiếp theo bạn mởi file web.php trong thư mục routes và chỉnh lại như sau:

Route::group(['prefix'=>'email'],function(){
	Route::get('/form', function () {
	    return view('pages.email');
	});
	Route::get('/success',function(){
		return view('pages.success');
	});
	Route::post('/form','EmailController@store');
});

Đồng thời bạn cần phải khai báo cấu hình mail nửa, ở đây mình cấu hình email qua .env bạn mở file env và chỉnh lại thông tin cấu hình mail như code bên dưới nhé

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=ten_mai_cua_ban
MAIL_PASSWORD=pass
MAIL_ENCRYPTION=tls

Vậy là xong rồi, giờ các bạn phải biên dịch project của bạn xem có lỗi gì không với câu lệnh: npm run dev

Nếu không có lỗi bạn tiến hành chạy câu lệnh: php artisan serve, và lên trình duyệt gõ: http://localhost:8000/email/send nhé 

Chúc các bạn làm thành công!

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)