LoginSignup
5
4

More than 5 years have passed since last update.

Google Cloud Launcher経由でSendGridを使う

Posted at

Google Cloud Launcher?

よく使われるソフトウェア、パッケージ、サービスをGCP上でデプロイ、統合することができる。

Google Cloud Platform Japan 公式ブログ: Cloud Launcher を使って人気のソフトウェア パッケージをデプロイする
Google Cloud Launcherで、よく使われる120あまりのオープンソースパッケージを素早くデプロイできる | TechCrunch Japan

SendGridのセットアップ

Cloud LauncherからSendGridの利用を開始できるようになっている。

Kobito.x6CxL0.png

プラン一覧。
今回は送信テストを行うだけなのでFreeプランを選択。
Freeでも月間12,000通の送信が可能。

Kobito.3Q1xXq.png

SendGridのユーザ登録(メールアドレス確認を含む)が完了すると、
Cloud LauncherからSendGridのサイト上にある設定画面に遷移することができるようになる。

Kobito.LBqs67.png

SendGridの管理画面上で、Create API Key > General API Key を選択し、APIキーを生成する。
キーに与える権限は項目ごとに細かく設定できるが、
今回はメールの送信をテストするだけなので Mail Send のみにフルアクセスを与える。

Kobito.EoOBpX.png

メール送信

今回はRubyから送信する。公式の sendgrid-ruby gemが用意されているので、それを使う。

GitHub - sendgrid/sendgrid-ruby: Official Ruby Gem for the SendGrid email Web API.

今回は折角なので送信元もCloud Launcherから立ち上げたRubyスタックを使う。
RubyスタックはBitnamiから提供されている。

Compute Engine 上で起動 を押して待つこと数分。

Kobito.TzIO6Z.png

ゾーンやマシンタイプ、ディスク容量はここで変更できる。
それらを設定して デプロイ を実行。

Kobito.HshHSx.png

デプロイ完了したらSSHログインして、
sendgrid-ruby gemをインストール。

$ ruby -v
ruby 2.2.5p319 (2016-04-26 revision 54774) [x86_64-linux]
$ sudo gem install sendgrid-ruby

sendgrid-ruby のリポジトリにサンプルがあるので、
これを実行してみる。

GitHub - sendgrid/sendgrid-ruby: Official Ruby Gem for the SendGrid email Web API.

require 'sendgrid-ruby'
include SendGrid

from = Email.new(email: 'test@example.com')
subject = 'Hello World from the SendGrid Ruby Library'
to = Email.new(email: 'test@example.com')
content = Content.new(type: 'text/plain', value: 'some text here')
mail = Mail.new(from, subject, to, content)

sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
response = sg.client.mail._('send').post(request_body: mail.to_json)
puts response.status_code
puts response.body
puts response.headers

送信に成功すれば response.status_code202(Accepted) が返る。

所感

実装面では別途SendGridを契約して利用するのと変わらないが、請求をまとめたり、プラン変更をGCPのコンソール上から行えるのは便利だと感じる。

利用料金は SendGrid から課金され、Google から請求されます。このサービスは Google Cloud Platform の無料試用の対象です。SendGrid サービスの解約、アップグレード、ダウングレードはいつでも行えます。請求金額は、解約または変更日を基準に日割計算されます。プランは日単位で課金されます。

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