LoginSignup
0
0

More than 1 year has passed since last update.

Cloud Functions で GmailAPI で メールを送信する方法 [Javascript]

Last updated at Posted at 2022-04-02

備忘録。

Google API を用意する

まず

の手順に沿って、認証情報の作成まで行います。途中、「スコープを追加または削除」の部分は readonly ではなく、send を選びます。

次に、

の 「OAuth 2.0 のための ID を得る」 に沿って、「Client ID」と「Client secret」と「Refresh token」と 「Refresh token」を 取得したのと同じページ から「Access Token」を取得します。

Cloud Functions を用意する

を参考にして、Cloud Functions の有効化・関数の作成を行います (Python の部分は、Nodejs に書き換えて下さい)。
関数の作成が出来たら、作成した関数をクリックし、その中から「ソース」のタブを選択して、以下のコードを加えます。
クライアントID・クライアントシークレット・リフレッシュトークン・アクセストークンを適宜書き換えて下さい。

package.json
{
  "name": "your-project-name",
  "version": "0.0.1",
  "dependencies": {
    "nodemailer": "^6.7.3"
  }
}
index.js
const nodeMailer = require("nodemailer")

exports.yourProject = (req, res) => {

    const transporter = nodeMailer.createTransport({
    host: "smtp.gmail.com",
    port: 465,
    secure: true,
    auth: {
      type: "OAuth2",
      user: "your-email@gmail.com",
      clientId: "クライアントID",
      clientSecret: "クライアントシークレット",
      refreshToken: "リフレッシュトークン",
      accessToken: "アクセストークン",
    }

  const mailOptions = {
    from: "your-email@gmail.com",
    to: "to-email@sample.com",
    subject: "Test Subject",
    text: "Test Text",
  }

  transporter.sendMail(mailOptions)
  .then(() => {
    res.status(200).send(response)
  })
  .catch(e => {
    res.status(500).send(e)
  })

}

これで、Cloud Functions から Gmail を送信することができました。

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