7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

node.jsでgoogleapisを使い、gmailでメール送信

Posted at

事前準備

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 これを見る限り、rawrequestBodyの中に入れるっぽいし、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の設定をこの書き出したファイルからやるとか、出来る

7
5
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
7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?