Skip to content

Instantly share code, notes, and snippets.

@zacharyhill
Created January 31, 2018 16:38
Show Gist options
  • Save zacharyhill/2ac6e31975896b1e52bb61aa12948fe1 to your computer and use it in GitHub Desktop.
Save zacharyhill/2ac6e31975896b1e52bb61aa12948fe1 to your computer and use it in GitHub Desktop.
const fs = require('fs');
const path = require('path');
const s3etm = require('s3-emails-to-mongo');
// MAKE THIS PART DYNAMIC LATER
s3etm.configure({
Bucket: 'zhillb-mail',
});
module.exports = async (req, res, next) => {
try {
const newMail = await s3etm();
// check if new mail has attachment(s), if so save them
newMail.forEach((msg) => {
try {
if (msg.attachments.length) {
msg.attachments.forEach(async (attachment) => {
const file = attachment.content;
const cid = attachment.cid;
const filePath = path.join(__dirname, '..', 'data/uploads', cid);
fs.writeFile(filePath, file, (err, data) => {
if (err) {
console.log('err with file: ', err);
} else {
console.log('saved file: ' + filePath);
console.log('mime type: ', attachment.contentType);
}
});
});
}
} catch(err) {
next(err);
}
});
res.json(newMail);
} catch(err) {
next(err);
}
};
@Announcement
Copy link

Announcement commented Jan 31, 2018

this should work equal as well, and should be pretty zippy ;)

const fs = require('fs')
const util = require('util')
const path = require('path')
const s3etm = require('s3-emails-to-mongo')

const directory = path.join(__dirname, '..', 'data', 'uploads')
const writeFile = util.promisify(fs.writeFile)

s3etm.configure({
  Bucket: 'zhillb-mail',
})

module.exports = async (request, response, next) => {
	const mail = await s3etm()

	await Promise.race(mail.map(async message => {
		return Promise.race(message.attachments.map(async attachment => {
			let { content, cid } = attachment
			let where = path.join(directory, cid)
			return writeFile(where, content)
				.then(it => {
					console.log(`saved file: ${where}`)
					console.log(`mime type: ${attachment.contentType}`)
				})
				.catch(exception => {
					console.log(`error with file: ${exception}`)
				})
		}))
	}))

	response.json(mail)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment