LoginSignup
47
43

More than 3 years have passed since last update.

Firebase Cloud Functionsを使ってGmail送信機能を作る

Last updated at Posted at 2019-07-27

Firebaseについて

FirebaseはGoogleが提供しているモバイルアプリ、Webアプリのプラットフォームのことで、バックエンド機能を体系的に提供している。Firebseを使うことによって、開発者はクライアントサイドの開発に専念することができる。
できることの例
◇Hosting
本番環境へのホスティング

◇Authentication
ユーザ認証/ログイン機能の実装

◇Databases
データベース

◇Functions
クライアントサイドで実行するには重すぎる処理をHTTPリクエストなどをトリガーに実行できるようにする機能

<以下参考>
Firebase公式:
https://firebase.google.com/?hl=ja
Firebaseの概要についてまとまっいたサイト:
https://www.topgate.co.jp/firebase01-what-is-firebase
Firebaseでできることについてまとまっていたサイト:
https://qiita.com/dogwood008/items/fa95b62ad151f823af70

そして、今回は Firebase Cloud Functions+node.js(nodemailer)でメール送信機能を実装してみる。
調べてみると、Vue.jsで実装している人は多いが、拡張性を高めるためにフレームワークは使用しないパターンで取り組む。

Firebase Cloud Functionsの初期設定

※Googleアカウントを持っていることは前提
※事前にnpmが使用できる環境を作ってあることは前提

①Firebaseでプロジェクトを作成する
・FirebaseコンソールにGoogleアカウントでログイン
 Firebaseコンソール: https://console.firebase.google.com/u/0/?hl=ja
・「プロジェクトを追加」からプロジェクトを追加する

<以下参考>
https://docs.kii.com/ja/samples/push-notifications/push-notifications-android-fcm/create-project/

②Firebase CLIをインストール

npm install -g firebase-tools

③Firebase CLIにログインする

firebase login

・ブラウザが立ち上がり、Googleアカウントを設定する画面が出てくるので、①のFirebase コンソールでプロジェクトを作成した Googleアカウントを選択、ログインする。
※Firebase CLIでログインするアカウントを変更したい場合は、

firebase logout

でログアウトすると別アカウントでログインできるようになる。

④Firebase Cloud Functionsのプロジェクトを作成する
A.プロジェクト用のディレクトリを作成し移動、下記コマンドを打つ

firebase init functions

下記のように表示される。

B.ここでセットアップするのは主に2つで
・ Project Setup
Firebase コンソールで作成したプロジェクトがあることを確認、選択。
firebase1.png

・Functions Setup
※基本的には画像と同じように選択すれば良いが、ここはそれぞれで要確認。
firebase2.png

C.ディレクトリの中にプロジェクトが作成されていることを確認
・functions/ の中にindex.jsというファイルが作成されている

$ls
firebase.json   functions

$cd functions/
index.js    package.json

⑤nodemailerとcorsをインストールする
※作業は functions/ で行う

npm install nodemailer cors

index.jsにメール送信のプログラムを書いていく

今回はクエリパラメータに送信先とメッセージ内容を含める仕様で実装。
これで、実際にアプリケーションで使う際も、送信先とメッセージ内容をその都度変更できる。

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const nodemailer = require('nodemailer');
const cors = require('cors')({origin: true});
const gmailEmail = functions.config().gmail.email;
const gmailPassword = functions.config().gmail.password;

admin.initializeApp();

// Using Gmail
let transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: gmailEmail,
        pass: gmailPassword
    }
});

// Sending the request
exports.sendMail = functions.https.onRequest((req, res) => {
    cors(req, res, () => {

        // Getting query parameter from http request
        const to = req.query.to;
        const msg = req.query.msg;

        const mailOptions = {
            from: gmailEmail,
            to: to,
            subject: 'This is a sample of email function',
            html: `${msg}`
        };

        // Getting results
        return transporter.sendMail(mailOptions, (erro, info) => {
            if(erro){
                return res.send(erro.toString());
            }
            return res.send('Sended');
        });
    });
});

いくつか解説
A.Gmailを使う際の、送信元のメールアドレスとパスワードについて
Firebaseでは、プロジェクト内で使える環境変数の設定が提供されている。

const gmailEmail = functions.config().gmail.email;
const gmailPassword = functions.config().gmail.password;

で事前に環境変数として設定したGmailアドレスとパスワードを取得する。

◇Firebaseでの環境変数の設定の仕方はこちらを参考
https://qiita.com/nerdyboy_cool/items/695c8af7ca8d22761927

(こんな感じ)

firebase functions:config:set gmail.email="hoge@gmail.com" gmail.password="fugafuga"

B.クエリパラメータから送信先メールアドレスとメッセージ内容を取得する仕組みについて

ここで取得している

const to = req.query.to;
const msg = req.query.msg;

⑥メール送信機能をデプロイする
プロジェクトの直下ディレクトリに戻る(functions/ の1つ上)

firebase deploy

そして以下のように表示されたら成功
firebase3.png

⑥デプロイしたfunctiosのURLを確認して、メールを送ってみる
A.Firebase コンソールに行き、該当プロジェクトの画面まで移動
左のメニュー欄のFunctionsのダッシュボードにHTTPリクセスト用のURLが表示さレているので取得

https://us-central1-****************/FUNCTIONAME

のようになっているので、クエリパラメータを指定して、ブラウザでURLを叩けばメールが送信される。

https://us-central1-****************/FUNCTIONAME?to=RECEIVER_EMAIL&msg=hogehoge"

このURLをHTMLのaタグとかで叩けば、アプリ内でサーバーを立ち上げなくてもGmail送信機能を使用することができる。

その他参考記事

Firebase Cloud Functionsについて:
https://qiita.com/HALU5071/items/e43729ac5b06b0506fbe
https://qiita.com/tdkn/items/2ed2b01f2656fc50da8c
今回の全体的な参考:
https://medium.com/@edigleyssonsilva/cloud-functions-for-firebase-sending-e-mail-1f2631d1022e
Vue.jsでやっている記事:
https://qiita.com/Hiroyuki1993/items/1ab9266ca6fc422113e3
https://qiita.com/ryo2132/items/7cdd6c86dd418095f74a#_reference-7ee779146fd0b678f3f9

47
43
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
47
43