事前準備
https://developers.google.com/gmail/api/quickstart/nodejs
とりあえずこの通りにして、ラベルが表示されるまでやってみる
スコープの変更
サンプルコードだとreadonlyだけなので、メール送信出来るようにスコープを変える
const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
を下のように変更
const SCOPES = ['https://www.googleapis.com/auth/gmail.send'];
既に出来上がっているtoken.json
はスコープが最初のままなので、このファイルを消す
メールの作成
メールは素のテキストで書くか、何らかのライブラリを使って組み立てるかして、最終的にはテキストにして、さらにBase64でエンコードしたものを使う必要がある
参考1
参考2
探した所、nodemailerのmail-composerが良さそうだった
import mailComposer from "nodemailer/lib/mail-composer"
const createMail = async (subject, to, text) => {
const mail = await new mailComposer({
to,
text,
subject,
textEncoding: "base64",
})
.compile()
.build()
const raw = Buffer.from(mail)
.toString("base64")
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "")
return raw
}
メールの送信
サンプルコードのlistLabels
の要領で、gmail
を作っておく
参考1
参考2 これを見る限り、raw
はrequestBody
の中に入れるっぽいし、typescriptの定義を見てもそうらしい(巷のサンプルコードはresource
だったりする)
(今回インストールのバージョンはnpm install googleapis@39 --save
)
const sendMail = async (subject, to, text) => {
const raw = await createMail(subject, to, text)
await gmail.users.messages.send({
userId: "me",
requestBody: {
raw,
},
})
}
自分のメールアドレスを動的に取る
fromアドレスをハードコードしたくない場合
const FROM_ADDRESS_PATH = "from.json"
gmail.users
.getProfile({ userId: "me" })
.then(({ data: { emailAddress } }) => {
fs.writeFile(
FROM_ADDRESS_PATH,
JSON.stringify({ from: emailAddress }),
(err) => {
if (err) return console.error(err)
console.log("from address stored:", FROM_ADDRESS_PATH)
}
)
})
こんな感じで自分のプロファイルを呼んで、ファイルに落とし込んでおいたりしてメール作成時にFROMの設定をこの書き出したファイルからやるとか、出来る