2
3

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.

AZURE Function AppでSendGridを使ってメール送信する

Last updated at Posted at 2017-10-19

準備

  • SendGridのアカウントを作り、メール送信権限のあるAPI KEYを作成する
  • AZURE Function を作成し、コード形式にjavascriptを指定する
  • 以下のコードのAPI KEY部分を書き換えてindex.jsを上書きする

コード

index.js
module.exports = function (context, req) {
    context.log('begin function');

    //アプリケーション設定で設定しておいたSendGridApiKeyを取得する
    var sendgridApiKey = process.env["SendGridApiKey"];

    var param1;

    if (req.query.name) {
        param1 = req.query.name;
    } else if ((req.body && req.body.name)) {
        param1 = req.body.name;
    }

    if (param1) {
        // send mail
        var http = require("https");

        var options = {
          "method": "POST",
          "hostname": "api.sendgrid.com",
          "port": null,
          "path": "/v3/mail/send",
          "headers": {
            "authorization": "Bearer " + sendgridApiKey,
            "content-type": "application/json"
          }
        };

        var req = http.request(options, function (res) {
          var chunks = [];

          res.on("data", function (chunk) {
            chunks.push(chunk);
          });

          res.on("end", function () {
            var body = Buffer.concat(chunks);
            console.log(body.toString());
          });
        });

        req.write(JSON.stringify({ personalizations:
           [ { to: [ { email: param1, name: param1 } ],
               subject: 'Hello, World!' } ],
          from: { email: 'test@example.com', name: 'Test Sender' },
          reply_to: { email: 'test@example.com', name: 'Test Sender' },
          subject: 'Hello, World!',
          content:
           [ { type: 'text/html',
               value: '<html><p>Hello, world!</p></html>' } ] }));
        req.end();

        //make response
        context.res = {
            // status: 200, /* Defaults to 200 */
            body: "Hello"
        };
    }
    else {
        context.res = {
            status: 400,
            body: "Please pass an email address on the query string or in the request body"
        };
    }
    context.done();
};

実行

メッセージボディかクエリ文字列に送信先アドレスを入力して実行する。
name:TO-MAIL-ADDRESS

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?