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