Sendery
Sendery

言語別 SDK

PHP

PHP から Sendery の公開済みテンプレートを送信します。

インストール
composer require sendery/php:^0.1.4
ソースコード

動作環境

PHP 8.3 以上と cURL 拡張が必要です。

設定

公開済みテンプレートを選び、プロジェクトの API キーを作成します。キーはサーバーの環境変数 SENDERY_API_KEY に保存してください。

Shell
export SENDERY_API_KEY="your_project_api_key"

メールを送信

your-template を公開済みテンプレートのキーに、data をそのテンプレートの変数に置き換えてください。

レスポンスにはメールの id と status が含まれます。変数のないテンプレートには data: [] を渡してください。

PHP
require 'vendor/autoload.php';

use Sendery\Client;

$sendery = new Client(getenv('SENDERY_API_KEY'));
$receipt = $sendery->send(
    to: '[email protected]',
    template: 'your-template',
    data: ['name' => 'Alex', 'action_url' => 'https://example.com/start'],
);

echo $receipt['id'];

メールの状態を取得

返された ID で配信状態を確認します。

PHP
$message = $sendery->get($receipt['id']);
echo $message['status'];

送信を再試行

一時的なエラーには retry(3) で最大 3 回追加で試行できます。毎回同じ冪等性キーとメールのデータを使ってください。

PHP
$email = $sendery->prepare(
    to: '[email protected]',
    template: 'your-template',
    data: ['name' => 'Alex', 'action_url' => 'https://example.com/start'],
    idempotencyKey: 'your-idempotency-key',
);
$receipt = $email->retry(3)->send();

エラー処理

SDK の例外を捕捉してステータスとコードを確認します。再試行の待機時間は秒単位です。以下では再試行の例で作成した email を使用します。

PHP
try {
    $receipt = $email->retry(3)->send();
} catch (\Sendery\ApiException $error) {
    error_log($error->status.': '.$error->errorCode);
    // $error->errors contains field-level validation errors.
    // $error->retryAfter is a delay in seconds, when provided.
    throw $error;
}

特定のバージョンを送信

公開履歴のバージョンを指定すると、テンプレートの更新後もその版を送信できます。指定しない場合は最新バージョンを使います。

PHP
$receipt = $sendery->prepare(
    to: '[email protected]',
    template: 'your-template',
    data: ['name' => 'Alex', 'action_url' => 'https://example.com/start'],
)->version(3)->send();

添付ファイル

attachments にファイルを渡します。ローカルファイルには Attachment::fromPath()、読み込み済みの内容には new Attachment() を使ってください。

最大10ファイル、合計5 MBまで送信できます。対応形式と上限は 添付ファイルのリファレンス を参照してください。

使用例
use Sendery\Attachment;

$sendery->prepare(
    to: '[email protected]',
    template: 'your-template',
    data: ['name' => 'Alex', 'action_url' => 'https://example.com/start'],
    idempotencyKey: 'your-idempotency-key',
    attachments: [
        Attachment::fromPath('/path/document.pdf', 'document.pdf', 'application/pdf'),
    ],
)->retry()->send();