Sendcorex
チュートリアル

Next.jsからメールを送る(App RouterとRoute Handler)

App Routerのやり方:Server ActionからREST APIを直接呼び出します。SMTPクライアントは不要です。

Sendcorexチーム·更新日 2026年9月21日·8分で読めます

ここでSMTPではなくRESTを使う理由

Next.jsのデプロイの多くはサーバーレスやエッジの関数で動いており、長時間の送信SMTP接続は不安定か、完全にブロックされています。Server ActionからHTTPSのPOSTを1回送れば、この問題を完全に回避できます。

お問い合わせフォーム用のServer Action

// app/actions.ts
'use server';

export async function sendContactMessage(formData: FormData) {
  const email = formData.get('email') as string;
  const message = formData.get('message') as string;

  const res = await fetch('https://graph.sendcorex.com/v3.0/emails', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.SENDCOREX_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      to: 'you@yourdomain.com',
      from: 'hello@yourdomain.com',
      replyTo: email,
      subject: 'New contact message',
      text: message,
    }),
  });

  if (!res.ok) throw new Error('Could not send message');
}

クライアントから呼び出したいならRoute Handlerでも

// app/api/contact/route.ts
export async function POST(request: Request) {
  const { email, message } = await request.json();

  const res = await fetch('https://graph.sendcorex.com/v3.0/emails', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.SENDCOREX_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ to: 'you@yourdomain.com', from: 'hello@yourdomain.com', replyTo: email, subject: 'New contact message', text: message }),
  });

  return Response.json({ ok: res.ok }, { status: res.ok ? 200 : 502 });
}

React Emailでレンダリング

単純な文字列より凝ったものは、@react-email/renderでReact EmailコンポーネントをHTMLにレンダリングし、結果をリクエストbodyのhtmlとして渡します。テンプレートを文字列連結ではなくコンポーネントとして管理できます。

チェックリスト

  • SENDCOREX_API_KEYはサーバー側だけに置き、NEXT_PUBLIC_で公開しないでください。
  • replyToには訪問者のアドレスを設定し、fromは認証済みのドメインのままにします。
  • ルートにレート制限をかけましょう。そうしないと、ボットがフォームを使って何千通ものメッセージを送ってきます。

数分で最初のメールを送信

無料アカウントを作成し、ドメインを認証して、上のコードを貼り付けましょう。

クレジットカード不要