Search code examples
amazon-web-servicesaws-lambdaamazon-ses

SES detect new email coming and do something


I want to create a simple system like this

  • Using SES to receive email (no need sending email)
  • Once new email coming, get email body and POST to another Api.

Anyone know what is the technical to do something like that?


Solution

  • I found the answer now.

    • Config SES to accept receiving emails
    • Using S3 as email server to store emails.

    On Email Receiving configuration (AWS console), Create rules set when new email coming and do 2 things

    • Store email to s3 bucket
    • Trigger Lambda function. Lambda function can read messageId but could not read email body, so need to use messageId as a Bucket Key and get body from s3 Bucket.
    • Do something you want with email body.

    Code for lambda function to read email body. Other steps are no need any code, just setting on AWS console

    import * as AWS from "@aws-sdk/client-s3";
    
    const bucket = "email-storing-bucket-name";
    
    async function getS3Object (bucketKey) {
      return new Promise(async (resolve, reject) => {
        const getObjectCommand = new AWS.GetObjectCommand({ Bucket: bucket, Key: bucketKey });
    
        try {
            const s3 = new AWS.S3({});
            const response = await s3.send(getObjectCommand);
            let responseDataChunks = [];
            response.Body.once('error', err => reject(err));
            
            response.Body.on('data', chunk => responseDataChunks.push(chunk));
            
            response.Body.once('end', () => resolve(responseDataChunks.join('')));
        } catch (err) {
            return reject(err);
        } 
      });
    }
    
    export const handler = async(event, context) => {
        console.log(JSON.stringify(event));
        
        const bucketKey = event.Records[0].ses.mail.messageId 
        
        console.log("email bucketKey == ", bucketKey);
        
        await getS3Object(bucketKey).then(data => {
            console.log("data ==", data);
            // TODO: Call webhook or do anything with email body here
        });
    };
    

    Hope this help someone else.