1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Next.js API Routes をうまく使ってSendGridからメール配信

Posted at

前提

  • SendGridは登録しておく(およそ1日くらいはかかるので前もってやっておく)
  • あらかじめAPIキーを取得しておく
sendgrid.ts
import sgMail from '@sendgrid/mail';
import type { NextApiRequest, NextApiResponse } from 'next';

import type { PostContactRequest } from 'api/v1/contact/postContact.type';

import { adminNotificationMessage } from 'email/adminNotificationMessage';
import { userNotificationMessage } from 'email/userNotificationMessage';

/**
 * @remarks 同じ名前のジェネリクスを定義
 * @generic T - 任意のリクエスト型
 */
export type NextAPIRequest<T> = Omit<NextApiRequest, 'body'> & {
  body: T;
};

/**
 *
 * @param req NextApiRequest<リクエスト型>
 * @param res NextApiResponse<レスポンス型>
 */
const handler = (
  req: NextAPIRequest<PostContactRequest>,
  res: NextApiResponse<{
    message: string;
  }>,
) => {
  if (req.method === 'POST') {
    if (typeof process?.env?.SENDGRID_API_KEY === 'undefined') {
      res.status(500).json({ message: 'SENDGRID_API_KEY is undefined' });
      return;
    }
    sgMail.setApiKey(process?.env?.SENDGRID_API_KEY ?? '');
    const notificationMsgForUser = userNotificationMessage(req);
    const notificationMsgForAdmin = adminNotificationMessage(req);
    (async () => {
      try {
        await sgMail.send(notificationMsgForAdmin);
        await sgMail.send(notificationMsgForUser);
      } catch (
        error: any // エラー型は知らなくてもいいのでanyでOK
      ) {
        console.log('error has occurred in sendgrid');
        console.error(error);
        if (error.response) {
          console.error(error.response.body);
          res.status(500).json(error.response.body);
        }
      }
    })();
    res.status(200).json({
      message: 'success',
    });
  }
};

export default handler;

 結論

  • 一日あたり15000通までなら無料で送信できる
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?