Created
January 15, 2021 08:42
-
-
Save vipin87/dcd69acfea95473ec7cc074a4c40fdf2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const AWS = require("aws-sdk"); | |
const csv = require("csv-parser"); | |
const { Readable } = require("stream"); | |
const simpleParser = require("mailparser").simpleParser; | |
const s3 = new AWS.S3(); | |
const documentClient = new AWS.DynamoDB.DocumentClient(); | |
const TableName = process.env.TABLE; | |
exports.handler = async (event) => { | |
const Bucket = event.Records[0].s3.bucket.name; | |
const Key = event.Records[0].s3.object.key; | |
const eml = await s3 | |
.getObject({ | |
Bucket, | |
Key, | |
}) | |
.promise(); | |
const parsed = await simpleParser(eml.Body); | |
const csvAttachments = parsed.attachments.filter( | |
(attachment) => attachment.contentType === "text/csv" | |
); | |
if (csvAttachments) { | |
const content = csvAttachments[0].content; | |
const stream = Readable.from(content.toString("utf-8")); | |
const promises = []; | |
stream | |
.pipe(csv()) | |
.on("data", (data) => { | |
var promise = documentClient | |
.put({ | |
TableName, | |
Item: data, | |
}) | |
.promise(); | |
promises.push(promise); | |
}) | |
.on("end", () => { | |
Promise.all(promises).then(() => { | |
console.log( | |
`Email from ${parsed.from.value.address} processed successfully` | |
); | |
}); | |
}); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment