12
8

More than 3 years have passed since last update.

Nuxt×CloudFunctions×SendGridでメールを送信する

Last updated at Posted at 2020-05-05

複雑な家庭の事情でどうしてもNuxt×CloudFunctions×SendGridでメールを送信する必要があったのでメモ。

Functionsの実装

ライブラリのインストール

Node.js用のライブラリがあるのでこれをインストールします。
https://github.com/sendgrid/sendgrid-nodejs

cd functions
npm install --save @sendgrid/mail

SendGridのAPIキーをセット

APIキーはfirebaseプロジェクトの環境構成にセットしちゃいます。

firebase functions:config:set sendgrid.apikey="hogehoge"

詳しく知りたい場合は公式説明で

index.jsを編集

/functions/index.js
const sgMail = require('@sendgrid/mail')
sgMail.setApiKey(functions.config().sendgrid.apikey)

exports.sendMail = functions
  .region('asia-northeast1')
  .https.onCall(
    async (data, context) => {
      const msg = {
        to: data.to,
        from: 'no-reply@test.com',
        cc: data.cc || '',
        bcc: data.bcc || '',
        replyTo: data.replyTo || '',
        templateId: data.templateId,
        dynamic_template_data: data.dynamic_template_data
      }
      try {
        await sgMail.send(msg)
      } catch (error) {
        console.error(error);
        if (error.response) {
          console.error(error.response.body)
      }
  }
})

Vueの実装

以下のような、招待メールを送るサンプルです
sample.png

index.vue
methods: {
  async sendMail(to_email, recipient_name, team_id, invite_url) {
    const sendInvite = await firebase
      .app()
      .functions('asia-northeast1')
      .httpsCallable("sendMail");
    sendInvite({
      to: to_email,
      templateId: '#SendGridのメールテンプレートのID',
      dynamic_template_data: {
        subject: 'TESTへの招待が届いています',
        name: recipient_name,
        team: team_id,
        url: invite_url
      }
    })
    .then((res) => {
      console.log(res.data)
    })  
  }
}

SendGridにはDynamicTemplatesという機能があり、作成したメールテンプレートのIDをtemplateIdとしてパラメータにセットし、テンプレート内で使用したい値をdynamic_template_dataの中に格納して渡すと、メール文面にいい感じにセットされます。

12
8
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
12
8