複雑な家庭の事情でどうしても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の実装
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の中に格納して渡すと、メール文面にいい感じにセットされます。