0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravelでメールを送信する

Last updated at Posted at 2020-05-22

参考:Laravelのmailableクラスでメール送信を行う[導入/入門編]

mailableクラス

$ php artisan make:mail sampleMailClass.php

を実行後、以下のように記述

laravel-project/app/Mail/sampleMailClass.php
<?php

namespace App\Mail;

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

class sampleMailClass extends Mailable
{
    use Queueable, SerializesModels;

    protected $name; // メンバ変数
    protected $content;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($mailData) // コンストラクタ
    {
        $this->name = $mailData['name'];
        $this->content = $mailData['content'];
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
         $this->text('view.page') // メール本文のイメージを記述したview 後ほど記述
                ->subject('お問い合わせが届きました')// メールタイトル
                ->with([
                    'name'    => $this->name,
                    'content' => $this->content
                ]); // viewに渡す引数
    }
}

簡単なビューページ

page.blade.php
<form action="controller">
 <label for="name">名前:</label>
 <input type="text" name="name" value="">
 <br>
<label for="content">内容</label> 
<textarea name="content" value=""></textarea>
 <br>
<button type="submit"  class="btn btn-primary">
 送信
 </button>


メールを送りました!!

名前:{{$name ?? ''}} {{-- 空チェック --}}
<br>
本文{{$content ?? ''}} {{-- 空チェック --}}

ルーティング

ルーティングは以下のように設定

web.php
Route::get('controller', 'Controller@notification'); 

コントローラー

$ php artisan make:controller Controller

実行後、以下のように記述

laravel-project/app/Mail/Controller.php
<?php

namespace App\Http\Controllers;

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

class Controller extends Controller
{
    public function notification(Request $request)
    {
        $contactData = [
            'name' => $request->name,
            'content' => $request->content                   
        ];
        $name = $request->name;
        $content = $request->content;
        $to = 'utsupedia@gmail.com';
        Mail::to($to)->send(new SendContact($contactData));

        return view('contact.result', ['contactData' => $contactData]);
    }
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?