Webhook APIを使ってメールを処理する(Google Cloud Functions + Java) (original) (raw)

Customers Mail Cloudではプログラム側からデータを取得したり、メールを送信するWeb APIの他に、Customers Mail Cloudでメールを受信した時にイベントを伝えてくれるWebhook APIが用意されています。

Webhook APIを使うことで、自前でメールサーバを立てずにメール受信のタイミングでシステムを起動させられるようになります。メールサーバを安定して動作させ続けるのはメンテナンスコストが大きいですが、Customers Mail Cloudを使うことで簡単にメールと連携したシステムが作れるようになるでしょう。

今回はGoogle Cloud Functionsで、Javaを使ってメールを処理する流れを紹介します。

フォーマットはJSONとマルチパートフォームデータ

Webhookの形式として、JSONとマルチパートフォームデータ(multipart/form-data)が選択できます。この二つの違いは、添付ファイルがあるかどうかです。JSONの場合、添付ファイルは送られてきません。メールに添付ファイルがついてくる可能性がある場合は、後者を選択してください。

Webhook設定ダイアログ

今回はJSONフォーマットにおけるWebhook処理について紹介します。

今回はローカルで開発する流れを紹介します。まず、適当なフォルダを作成します。今回はcmcとします。

mkdir cmc cd cmc

ソース ディレクトリとソースファイルを格納するプロジェクト構造を作成します。

mkdir -p src/main/java/functions touch src/main/java/functions/HelloWorld.java

HelloWorld.java を編集します。

package functions;

import com.google.cloud.functions.HttpFunction; import com.google.cloud.functions.HttpRequest; import com.google.cloud.functions.HttpResponse; import java.io.BufferedWriter; import java.io.IOException;

public class HelloWorld implements HttpFunction { @Override public void service(HttpRequest request, HttpResponse response) throws IOException { BufferedWriter writer = response.getWriter(); writer.write("ok"); } }

次に build.gradle を作成します。

apply plugin: 'java'

repositories { jcenter() mavenCentral() } configurations { invoker }

dependencies { // https://mvnrepository.com/artifact/com.google.code.gson/gson implementation group: 'com.google.code.gson', name: 'gson', version: '2.7'

// Every function needs this dependency to get the Functions Framework API. compileOnly 'com.google.cloud.functions:functions-framework-api:1.1.0'

// To run function locally using Functions Framework's local invoker invoker 'com.google.cloud.functions.invoker:java-function-invoker:1.3.1'

// These dependencies are only used by the tests. testImplementation 'com.google.cloud.functions:functions-framework-api:1.1.0' testImplementation 'junit:junit:4.13.2' testImplementation 'com.google.truth:truth:1.4.0' testImplementation 'org.mockito:mockito-core:5.10.0'

}

// Register a "runFunction" task to run the function locally tasks.register("runFunction", JavaExec) { main = 'com.google.cloud.functions.invoker.runner.Invoker' classpath(configurations.invoker) inputs.files(configurations.runtimeClasspath, sourceSets.main.output) args( '--target', project.findProperty('run.functionTarget') ?: '', '--port', project.findProperty('run.port') ?: 8080 ) doFirst { args('--classpath', files(configurations.runtimeClasspath, sourceSets.main.output).asPath) } }

ライブラリをインストールします。

gradle build

そして、以下のようにコマンドを実行します。

gradle runFunction -Prun.functionTarget=functions.HelloWorld

これで、 http://localhost:8080 にてサーバーが立ち上がります。

Webhookで受け取るデータについて

Webhookを使ってPOSTされるJSONデータは、次のようになっています。

{ "filter": "info@smtps.jp", "headers": [ {"name": "Return-Path", "value": "user@example.com"}, : {"name": "Date", "value": "Thu, 27 Apr 2023 15:56:26 +0900"} ], "subject": "Webhookのテスト", "envelope-to": "user@smtps.jp", "server_composition": "sandbox", "html": "<div dir=\\\\\\\\"ltr\\\\\\\\">Webhookのテスト用メールです。

...
", "text": "Webhookのテスト用メールです。\\\\\\\\r\\\\\\\\n\\\\\\\\r\\\\\\\\n--\\\\\\\\r\\\\\\\\n...", "envelope-from": "info@smtps.jp" }

Javaのコード

処理は HelloWorld.javaservice 関数内に記述します。

public void service(HttpRequest request, HttpResponse response) throws IOException { BufferedWriter writer = response.getWriter();

writer.write("ok");

}

送られてくるデータは request.getReader() で受け取れます。このJSON文字列を gson.fromJson でパースします。

JsonObject body = gson.fromJson(request.getReader(), JsonObject.class);

後は、このオブジェクトから必要な情報を取り出して処理を行います。

System.out.println(body.get("filter").getAsString());
System.out.println(body.get("subject").getAsString());

Webhookの結果は管理画面で確認

Webhookでデータが送信されたログは管理画面で確認できます。送信時のAPIキー設定など、HTTPヘッダーを編集するといった機能も用意されていますので、運用に応じて細かなカスタマイズが可能です。

Webhookログ

まとめ

メールと連携したシステムはよくあります。通常、メールサーバを立てて、その中で処理することが多いのですが、メールサーバが落ちてしまうとシステムが稼働しなくなったり、メール文面の解析が煩雑でした。Customers Mail Cloudを使えばそうした手間なくJSONで処理できて便利です。

受信サーバ | Customers Mail Cloud