Laravel 13系でMailpitに対してテキスト・HTMLメールを送信する方法
Laravel 13系でMailpitに対してテキスト・HTMLメールを送信したい。また、ブラウザよりアクセスした際に「html_flg=1」のGETパラメータがあればHTMLメールを、なければテキストメールを送信したい。以下に対応方法をメモ。
対応方法
メール送信用(Mailable)Classを作成
サーバにSSH接続して以下でClassを作成する。
# 通常の場合 php artisan make:mail TestMail # Podmanコンテナ環境の場合 podman exec -w 【Laravelのディレクトリ】 【コンテナ名】 php artisan make:mail TestMail
設定ファイル(.env)
以下を追記あるいは変更する。
MAIL_MAILER=smtp MAIL_HOST=【コンテナ名】 MAIL_PORT=1025 MAIL_ENCRYPTION=null
メール送信用Class(/app/Mail/TestMail.php)
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Attachment;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
class TestMail extends Mailable
{
use Queueable, SerializesModels;
public string $html_flg;
/**
* Create a new message instance.
*/
public function __construct(bool $html_flg)
{
$this->html_flg = $html_flg;
}
/**
* Get the message envelope.
*/
public function envelope(): Envelope
{
$subject = ($this->html_flg) ? 'HTMLメールタイトル' : 'テキストメールタイトル';
return new Envelope(
subject: $subject,
);
}
/**
* Get the message content definition.
*/
public function content(): Content
{
if ($this->html_flg) {
return new Content(
view: 'mail.html',
);
} else {
return new Content(
text: 'mail.text',
);
}
}
/**
* Get the attachments for the message.
*
* @return array<int, Attachment>
*/
public function attachments(): array
{
return [];
}
}
テキストメールの中身(/resources/views/mail/text.blade.php)
<html lang="ja"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>HTMLmail</title> </head> <body> <h1>Laravelからのテスト送信です。</h1> <br> 改行 <br> <h2>Laravelからのテスト送信です。</h2> </body> </html>
HTMLメールの中身(/resources/views/mail/html.blade.php)
Laravelからのテスト送信です。 改行 Laravelからのテスト送信です。
ルーティング設定(/routes/web.php)
以下を追記。
# メール送信用
use App\Mail\TestMail;
use Illuminate\Support\Facades\Mail;
Route::get('/mail_test', function (Request $request) {
try {
$html_flg = (bool)$request->query('html_flg');
Mail::to('to@test.com')->send(new TestMail($html_flg));
return '送信成功';
} catch (\Exception $e) {
return '送信失敗: ' . $e->getMessage();
}
});
動作確認
ブラウザから「/mail_test?html_flg=1」にアクセスするとHTMLメールが、「/mail_test」にアクセスするとテキストメールが送信される筈。
注意点
「$html_flg」ではなく「$html」と定義した場合、Laravel内部の基底クラスのプロパティと衝突するみたく、エラーになるので注意。
あと「$html_flg」の中身は厳密にチェックしていない点にも注意。
リファレンス
メール
https://laravel-jp.toolboxforweb.xyz/docs/mail
メーラブルの生成
関連記事
-
-
Podmanコンテナ環境にLaravel 13系をインストールしHello Worldページ表示まで行う方法
先日Podmanコンテナ環境(PHP 8.4.25)にCodeIgniterをイ ...
-
-
Laravel 13系でGET / POSTパラメータを受け取って出力する方法
Laravel 13系でフォームから送信したGET / POSTパラメータを受け ...
-
-
Laravelのディレクトリ構造・バージョン・DB接続情報確認
Laravelで作成されているシステムに携わることがあった。しかしながら当方La ...
-
-
Laravel 13系でエラーログ設定と出力及び確認方法
Laravelのエラーログはデフォルト設定だと同じファイルに無制限に追記していく ...
-
-
Podmanコンテナ環境のLaravelのキャッシュクリア方法
Laravelで何らかのファイルを編集し、アップロードしてもうまく動かない場合が ...