フレームワーク連携
Laravel
Laravel Mail と Notifications を使い、Sendery のテンプレートでトランザクションメールを送信します。
composer require sendery/laravel:^0.1.4動作環境
Laravel 13、PHP 8.3 以上と cURL 拡張が必要です。
アプリの設定
プロジェクトの API キーを作成し、以下を .env に追加します。インストール後は sendery メーラーを使えます。MAIL_FROM_ADDRESS にはプロジェクトの送信者アドレスを指定してください。
SENDERY_API_KEY=your_project_api_key
[email protected]
MAIL_FROM_NAME="Your app"メールを送信
TemplateMail で公開済みテンプレートを送信します。your-template を公開済みテンプレートのキーに、data をそのテンプレートの変数に置き換えてください。送信者は Sendery のプロジェクトで設定します。
use Illuminate\Support\Facades\Mail;
use Sendery\Laravel\TemplateMail;
Mail::mailer('sendery')->to('[email protected]')->send(
new TemplateMail('your-template', [
'name' => 'Alex',
'action_url' => 'https://example.com/start',
])
);キューで送信
バックグラウンドで送信するには queue() を使います。Laravel のキューワーカーで、失敗したジョブの同じメールを安全に再試行できます。
use Illuminate\Support\Facades\Mail;
use Sendery\Laravel\TemplateMail;
Mail::mailer('sendery')->to('[email protected]')->queue(
new TemplateMail('your-template', [
'name' => 'Alex',
'action_url' => 'https://example.com/start',
])
);パスワード再設定とメール認証
各メールに使う公開済みテンプレートを選び、AppServiceProvider::boot() に以下を追加します。Laravel が name と action_url を渡すので、テンプレートのリンクには {{ action_url }} を使ってください。
通知の言語で送るには useNotificationLocale: true を追加し、翻訳を公開します。
// app/Providers/AppServiceProvider.php
use Sendery\Laravel\Sendery;
public function boot(): void
{
Sendery::useBuiltInNotifications(
passwordResetTemplate: 'your-reset-template',
emailVerificationTemplate: 'your-verification-template',
);
}独自の通知
Laravel の通知から送るには SenderyChannel を使います。toSendery() からテンプレートのキーと変数を返してください。
use Illuminate\Notifications\Notification;
use Sendery\Laravel\SenderyChannel;
class TemplateNotification extends Notification
{
public function __construct(
public string $template,
public array $data,
) {}
public function via(object $notifiable): array
{
return [SenderyChannel::class];
}
public function toSendery(object $notifiable): array
{
return ['template' => $this->template, 'data' => $this->data];
}
}
$user->notify(new TemplateNotification('your-template', ['name' => 'Alex']));エラー処理
送信に失敗すると例外が発生します。タイムアウトや一時的なエラーにはキューでの再試行を使います。API キー、テンプレート、請求のエラーは原因を修正してから再送してください。
特定のバージョンを送信
公開履歴のバージョンを指定すると、テンプレートの更新後もその版を送信できます。指定しない場合は最新バージョンを使います。
use Illuminate\Support\Facades\Mail;
use Sendery\Laravel\TemplateMail;
$email = (new TemplateMail('your-template', [
'name' => 'Alex',
'action_url' => 'https://example.com/start',
]))->version(3);
Mail::mailer('sendery')->to('[email protected]')->send($email);添付ファイル
Laravelの attachData() メソッドで TemplateMail にファイルを添付します。
最大10ファイル、合計5 MBまで送信できます。対応形式と上限は 添付ファイルのリファレンス を参照してください。
use Illuminate\Support\Facades\Mail;
use Sendery\Laravel\TemplateMail;
$email = new TemplateMail('your-template', [
'name' => 'Alex',
'action_url' => 'https://example.com/start',
], idempotencyKey: 'your-idempotency-key');
$email->attachData(file_get_contents('/path/document.pdf'), 'document.pdf', [
'mime' => 'application/pdf',
]);
Mail::mailer('sendery')->to('[email protected]')->send($email);