前提
- 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通までなら無料で送信できる