74
loading...
This website collects cookies to deliver better user experience
imap: this helps us connect to the email server and retrieve emails as a stream
mailparser: we are going to use this to parse the stream data into a readable format.
mkdir imap-client
npm init -y
touch index.js
yarn add imap mailparser
const Imap = require('imap');
const {simpleParser} = require('mailparser');
const imapConfig = {
user: '[email protected]',
password: 'secret',
host: 'imap.gmail.com',
port: 993,
tls: true,
};
const getEmails = () => {
try {
const imap = new Imap(imapConfig);
imap.once('ready', () => {
imap.openBox('INBOX', false, () => {
imap.search(['UNSEEN', ['SINCE', new Date()]], (err, results) => {
const f = imap.fetch(results, {bodies: ''});
f.on('message', msg => {
msg.on('body', stream => {
simpleParser(stream, async (err, parsed) => {
// const {from, subject, textAsHtml, text} = parsed;
console.log(parsed);
/* Make API call to save the data
Save the retrieved data into a database.
E.t.c
*/
});
});
msg.once('attributes', attrs => {
const {uid} = attrs;
imap.addFlags(uid, ['\\Seen'], () => {
// Mark the email as read after reading it
console.log('Marked as read!');
});
});
});
f.once('error', ex => {
return Promise.reject(ex);
});
f.once('end', () => {
console.log('Done fetching all messages!');
imap.end();
});
});
});
});
imap.once('error', err => {
console.log(err);
});
imap.once('end', () => {
console.log('Connection ended');
});
imap.connect();
} catch (ex) {
console.log('an error occurred');
}
};
getEmails();
node index.js
Let's do a bit of explanation.
imap.search(['UNSEEN', ['SINCE', new Date()]], (err, results) => {}
simpleParser(stream, async (err, parsed) => {}
imap.addFlags(uid, ['\\Seen'], () => {}