LaravelのartisanコマンドでLaravelのMailableクラスを継承したクラスを生成します。
# php artisan make:mail MailSend
INFO Mail [app/Mail/MailSend.php] created successfully.
今回はローカルからのみの送信専用なので、smtp経由でなくsendmail経由でメール送信します。
.envファイルのメール以下箇所を修正
MAIL_MAILER=sendmail
MAIL_HOST=localhost
MAIL_PORT=null
修正後にConfigのキャッシュをクリアしておきます。
php artisan config:cache
[Laravelインストールディレクトリ]/app/Mail/MailSend.phpが生成されます。
__constructを編集。引数をプライベートプロパティに代入
<?php
public function __construct(array $info = [])
{
$this->info = $info;
}
buildメソッド作成。引数をプライベートプロパティに代入
<?php
public function build()
{
return $this->to($this->info['to'])
->from($this->info['from'], $this->info['from_name'])
->subject($this->info['subject'])
// HTMLメールのテンプレートファイル名
// ->view($this->info['view_html'])
// プレーンメールのテンプレートファイル名
->text($this->info['view_plain'])
// テンプレートファイル内で使用する変数
->with([
'args' => $this->info['args'],
]);
}
テストのコントローラーを作成してメール送信テスト。
テストのGmailにメールを送信
<?php
class TestController extends Controller
{
use Illuminate\Support\Facades\Mail;
use App\Mail\MailSend;
public function index(){
// メールテスト
Mail::send(new MailSend([
'to' => 'XXXX@gmail.com',
'from' => XXXX@XXXX.jp',
'from_name' => '送信元名',
'subject' => '件名てすと',
'view_plain' => 'noreply_plain',
'args' => ['test' => 'test']
]);
}
}
メール送信完了を確認
Gmailの迷惑メールフォルダに届いたので、迷惑メールにならないように
こちらでサーバー側の設定を調査します。