Skip to content

Instantly share code, notes, and snippets.

@bekce
Created February 13, 2017 11:46
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bekce/2fedd3fdcd4a532169f9e3d193623a57 to your computer and use it in GitHub Desktop.
Save bekce/2fedd3fdcd4a532169f9e3d193623a57 to your computer and use it in GitHub Desktop.
Node.js IMAP client with parsing

This example connects to an imap server and retrieves emails

npm install imap mailparser

// trust all certificates
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
var Imap = require('imap'),
inspect = require('util').inspect;
var fs = require('fs');
const simpleParser = require('mailparser').simpleParser;
var imap = new Imap({
user: 'test@local',
password: 'test',
host: 'localhost',
port: 32796,
tls: true
});
function openInbox(cb) {
imap.openBox('INBOX', true, cb);
}
imap.once('ready', function() {
openInbox(function(err, box) {
if (err) throw err;
console.log(box.messages.total + ' message(s) found!');
// 1:* - Retrieve all messages
// 3:5 - Retrieve messages #3,4,5
var f = imap.seq.fetch('1:1', {
bodies: ''
});
f.on('message', function(msg, seqno) {
console.log('Message #%d', seqno);
var prefix = '(#' + seqno + ') ';
msg.on('body', function(stream, info) {
// use a specialized mail parsing library (https://github.com/andris9/mailparser)
simpleParser(stream, (err, mail) => {
console.log(prefix + mail.subject);
console.log(prefix + mail.text);
});
// or, write to file
//stream.pipe(fs.createWriteStream('msg-' + seqno + '-body.txt'));
});
msg.once('attributes', function(attrs) {
console.log(prefix + 'Attributes: %s', inspect(attrs, false, 8));
});
msg.once('end', function() {
console.log(prefix + 'Finished');
});
});
f.once('error', function(err) {
console.log('Fetch error: ' + err);
});
f.once('end', function() {
console.log('Done fetching all messages!');
imap.end();
});
// search example
// imap.search([ 'UNSEEN', ['SINCE', 'May 20, 2010'] ], function(err, results) {
// if (err) throw err;
// var f = imap.fetch(results, { bodies: '' });
// ...
// }
});
});
imap.once('error', function(err) {
console.log(err);
});
imap.once('end', function() {
console.log('Connection ended');
});
imap.connect();
@chetanpatel6
Copy link

how to get FROM address?
mail.from isn't working.

@sdejean28
Copy link

sdejean28 commented Jul 8, 2020

you can get this from headers:

mail.headers.get('from')

but "mail.from" should give you the same things.

But you get a JSON object not directly a string with email address:
{ value:
[ { address: 'adresse@domain.tld',
name: 'sender name' } ],
html:
'sender name in html format',
text: 'sender name with email' }

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