LoginSignup
3
2

More than 5 years have passed since last update.

Azure Function からSendGridバインドを使ってメールを送る

Last updated at Posted at 2017-10-10

Azure上で、SendGridバインディングを使って、お手軽にユーザー宛にメールを送る仕組みを作っているので、SendGridバインディングの使い方をまとめてみた。npmでSendGridのクライアントをインストールする必要もなく、サクッとメール配信が作成できるので便利。

用意するもの

  • SendGrid API Key
    • SendGridもAzureから簡単にアカウントをオープンできるので便利 :thumbsup:
  • Azure Function CLI
    • インストール方法は、上の記事を参考に。

セットアップ手順

Azure FunctionのApp Setting にSendGridのAPI Keyを追加

予め取得しておいたSendGrid のAPI KeyをFunctionで利用できるようにするため、ポータルからApp Settingsを追加。以下、例としてSendGridAPIKey として追加。

func コマンドでFunctionを作成

トリガーは何でも良いので、とりあえず作ってみる。
func function new コマンドは対話的に新しいFunctionを作成できます。
ここではお手軽なHTTPトリガーにしました。

$ func function new
Select a language:
1. C#
2. JavaScript
Choose option: 2
JavaScript
Select a template:
1. BlobTrigger
2. HttpTrigger
3. QueueTrigger
4. TimerTrigger
Choose option: 2
HttpTrigger
Function name: [HttpTriggerJS] SendEmail
Writing /Users/tatsuya.b.sato/Projects/private/myfunctions/SendEmail/index.js
Writing /Users/tatsuya.b.sato/Projects/private/myfunctions/SendEmail/sample.dat
Writing /Users/tatsuya.b.sato/Projects/private/myfunctions/SendEmail/function.json

function.json にSendGridバインディングを追加

SendEmail/function.json
{
  "disabled": false,
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req"
    },
    {
      "name": "$return",
      "type": "sendGrid",
      "direction": "out",
      "apiKey": "SendGridAPIKey",
      "subject": "Test from Azure Function!",
      "text": "Hi, Azure Function!"
    }
  ]
}

バインディングの詳細については、ドキュメントを参照。

Function を書く。

HTTPトリガーで指定されたメールアドレスにメールを送るFunctionを書いてみる。

SendEmail/index.js
module.exports = function (context, req) {
    var email = req.query.email;

    var message = {
      personalizations: [
        { to: [ { email: email } ] }
      ],
      from: { email: "no-reply@example.com" }
    };

    context.done(null, message);
};

デプロイ

gitやFTPでデプロイすれば完了。
上の例だと、HTTPのURLパラメーターにemail=foo@example.com のように宛先を指定することで、送信できる。
ここでは手軽さのためにHTTPトリガーを使いましたが、どこからでも誰からでも使えてしまうのは危ないので、業務ではQueueトリガーなど適切な方法に切り替えましょう。

SendGrid のメッセージとして指定できるJSONの値は、どうやらv3 Mail Sendみたいです。

参考

3
2
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
3
2