TypeScript + Node.js + Expressを使ってSendGridからメールを配信する方法

SendGridに登録し、API Keyを取得

SendGrid | クラウドメール配信サービス・メルマガ配信システム
世界中のマーケターや開発者が使っているメール配信サービス「SendGrid」。月間1,000億通以上の配信実績、高いメール到達率!豊富なAPIでシステム連携も簡単に!

まずは上記のリンクからSendGridのアカウントを作成してください。

作成後、API Keyを取得します。

環境構築

Node.jsの環境構築をします。

下記のコードでライブラリをインストールしてください。

npm install @sendgrid/mail

実装コード紹介

続いてコードのご紹介です。

メールを送信する関数と、関数の呼び出し元を実装します。

import sendgrid from '@sendgrid/mail'

export const SendGrid = {
  async sendMail(data: {
    to: string;
    bcc: string;
    from: string;
    subject: string;
    text: string;
  }) {
    sendgrid.setApiKey("自身のAPI Key");
    const msg = {
    to: data.to,
    bcc: data.bcc,
    from: data.from,
    subject: data.subject,
    text: data.text,
  };

  try {
    const [response] = await sendgrid.send(msg)
    console.info(response)
  } catch(error) {
    console.error(error)
  }
 }
}
import { SendGrid } from "./send-grid";

/**
 * @param req
 * @param res
 * フロントから送りたいパラメータに値を入れて関数を呼び出す(フロント部分は割愛します)
 */
export const sendTestTargetingMail = async (req: Request, res: Response) => {
  try{
    const result = await SendGrid.sendMail({
      to: req.body.to
    //複数宛先に送りたい時
    //to: [req.body.testEmails[0],req.body.testEmails[1]]
      bcc: req.body.bcc,
      from: "noreply@example.com",
      subject: req.body.title,
      text: req.body.body,
    })
    return res.status(200).json(result)
  } catch (e) {
    res.status(500).json({ errorMessage: e.message })
  }

}

今回の引数としては

  • to:宛先のメールアドレス
  • bcc:BCC先のメールアドレス
  • from:送信元のメールアドレス
  • subject:メールの題名
  • text:メールの内容本文

引数は下記のドキュメントに記載のパラメータを使用できます。

メール送信API(V3 Mail Send API) - ドキュメント | SendGrid
このエンドポイントを使うことでWeb API v3(最新バージョンのAPI)経由でメールを送信できます。7つのプログラミング言語(C#, Go, Java, NodeJS, PHP, Python, Ruby)でライブラリを提供しています。

これで、フロントで入力したメールアドレスにnoreply@example.comを送信元としてメールを送ることができます。

以上、よければ参考にいただければ幸いです。

コメント

タイトルとURLをコピーしました