SES で受信したメールを Lambda (C#) で読む方法
開発環境
・Windows10 Pro
・VisualStudio2017
Visual Studio のインストール | Microsoft Docs
必要なもの
・AWS ToolKit for VisualStudio
AWS Toolkit for Visual Studio | AWS
・AWSSDK.S3
NuGet Gallery | AWSSDK.S3 3.3.102.18
・Amazon.Lambda.A3Events
NuGet Gallery | Amazon.Lambda.S3Events 1.1.0
1. Route 53 と SES の設定を行う
以下の記事を参考に設定を行います。
dev.classmethod.jp
注意する点についてまとめます。
・Recipients
記事に従ってMXレコードで設定したドメインを入力します。
これでドメインが一致するメールアドレスなら受信できます。
設定の詳細については以下のドキュメントを参考にしてください。
docs.aws.amazon.com
2. Lambda のトリガーを S3 の Putイベントに設定する
LambdaのコンソールからS3をトリガーに設定します。
3. Lambda Function をデプロイする
以下を NuGet からインストールします。
・AWSSDK.S3
NuGet Gallery | AWSSDK.S3 3.3.102.18
・Amazon.Lambda.A3Events
NuGet Gallery | Amazon.Lambda.S3Events 1.1.0
メール内容をログに出力するLambda関数を記述します。
using System; using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.Lambda.S3Events; using Amazon.S3; using System.IO; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace AWSLambda1 { public class Function { private readonly AmazonS3Client S3Client; public Function() { S3Client = new AmazonS3Client(); } public async Task FunctionHandler(S3Event evnt, ILambdaContext context) { var s3Event = evnt.Records?[0].S3; if (s3Event == null) { return; } try { Console.WriteLine($"Handler: getting object {s3Event.Object.Key} from bucket {s3Event.Bucket.Name}."); var response = await this.S3Client.GetObjectAsync(s3Event.Bucket.Name, s3Event.Object.Key); using (var stream = response.ResponseStream) { TextReader tr = new StreamReader(stream); var s3Document = tr.ReadToEnd(); Console.WriteLine("Handler: Mail processed successfully"); Console.WriteLine(s3Document); return; } } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); Console.WriteLine("Handler: FAILED to process mail successfully"); throw; } } } }
参考サイト
My First AWS Lambda Function in C# - Minimalist
Compress images with C#, .NET Core, AWS Lambda and TinyPNG • Jerrie Pelser's Blog
AWS Solutions Architect ブログ: 【AWS Developer Blog】Visual StudioでAWS Lambdaプロジェクトを使用する
AWS SES + S3でメール受信環境を構築 AWSで無料サーバ証明書_1 | システムガーディアン株式会社
AWS SESでメールを受信してS3へ保管してみる - Qiita