SvelteKit × Resendでメール送信を実装した話

ResendはシンプルなAPIでメール送信できるサービスです。無料枠で月3,000通まで送れます。SvelteKit + Cloudflare Workersとの組み合わせでお問い合わせフォームを実装しました。


セットアップ

1. Resendのアカウント作成とAPIキー取得

  1. resend.com でアカウント作成
  2. ダッシュボード → API KeysCreate API Key
  3. 作成したAPIキーをコピー

2. SDKをインストール

npm install resend

3. APIキーをシークレットに登録

.dev.vars(ローカル用):

RESEND_API_KEY=re_xxxxxxxxxx

本番用:

npx wrangler secret put RESEND_API_KEY

4. src/app.d.ts に型を追加

interface Platform {
  env: {
    RESEND_API_KEY: string;   // ← 追加
    // ... 他のenv
  };
}

実装例:お問い合わせフォーム

src/routes/contact/+page.server.ts

import type { Actions } from './$types';
import { fail } from '@sveltejs/kit';
import { Resend } from 'resend';

export const actions: Actions = {
  send: async ({ request, platform }) => {
    const data = await request.formData();
    const name = data.get('name') as string;
    const message = data.get('message') as string;

    if (!name || !message) {
      return fail(400, { error: '名前とメッセージを入力してください' });
    }

    const resend = new Resend(platform!.env.RESEND_API_KEY);

    try {
      const result = await resend.emails.send({
        from: 'onboarding@resend.dev',
        to: 'your-email@example.com',
        subject: `お問い合わせ: ${name}`,
        html: `<p><strong>${name}</strong>からのメッセージ:</p><p>${message}</p>`,
      });
      console.log('Resend result:', result);
      return { success: true };
    } catch (e) {
      console.error('Resend error:', e);
      return fail(500, { error: 'メール送信に失敗しました' });
    }
  },
};

src/routes/contact/+page.svelte

<script lang="ts">
  import { enhance } from '$app/forms';
  let { form } = $props();
</script>

<h1>お問い合わせ</h1>

{#if form?.success}
  <p style="color: green">送信しました!</p>
{:else}
  <form method="POST" action="?/send" use:enhance>
    <input type="text" name="name" placeholder="お名前" /><br />
    <textarea name="message" placeholder="メッセージ"></textarea><br />
    <button type="submit">送信</button>
    {#if form?.error}
      <p style="color: red">{form.error}</p>
    {/if}
  </form>
{/if}

送信履歴の確認

resend.comEmails で送信履歴を確認できます。

ステータス 内容
Delivered 送信成功
Bounced 送信失敗(メールアドレスが無効など)
Failed API呼び出し自体が失敗

ドメイン未認証時の制限

Resendはドメインを認証していない状態では送信先に制限があります。

状態 送信先 from アドレス
ドメイン未認証(テスト) 自分のアカウントのメールアドレスのみ onboarding@resend.dev のみ
ドメイン認証済み 任意のメールアドレス 認証済みドメインのアドレス

ドメイン未認証の状態で別のアドレスに送ろうとすると以下のエラーが出ます:

You can only send testing emails to your own email address.
To send emails to other recipients, please verify a domain at resend.com/domains.

テスト用途の場合

to を自分のアカウントアドレスに固定するだけでOKです。

本番運用する場合

  1. resend.com/domains でドメインを追加
  2. DNSにTXTレコード・MXレコードを追加して認証
  3. from を認証済みドメインのアドレスに変更
from: 'noreply@yourdomain.com',  // 認証済みドメインのアドレス

まとめ

  • npm install resend でSDKをインストールして resend.emails.send() を呼ぶだけで送れる
  • APIキーは .dev.varswrangler secret put で管理する
  • ドメイン未認証の状態では自分のアカウントアドレス宛にしか送れない
  • 本番運用には独自ドメインの認証が必要
← トップページに戻る