Last active
May 2, 2021 17:08
-
-
Save oslund/c92d603cc9dca935f84d to your computer and use it in GitHub Desktop.
Getting Gmail message by message ID (X-GM-MSGID) with node-imap
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
var Imap = require('imap'); | |
var crypto = require("crypto"); | |
var inspect = require('util').inspect; | |
function xoauth2 () { | |
var authData = [ | |
'[email protected]', | |
'auth=Bearer ' + 'ysadfffeDoedTjyUjS-sample-access-token-65aHk9CrnQAN96hxLLD6HTg', | |
'', | |
'' | |
]; | |
return new Buffer(authData.join('\x01'), 'utf-8').toString('base64'); | |
} | |
imap = new Imap({ | |
user: '[email protected]', | |
xoauth2: xoauth2(), | |
host: 'imap.gmail.com', | |
port: 993, | |
tls: true | |
}); | |
/** | |
* Gmail's system folders: | |
* INBOX | |
* [Gmail]/All Mail | |
* [Gmail]/Drafts | |
* [Gmail]/Sent Mail | |
* [Gmail]/Spam | |
* [Gmail]/Starred | |
* [Gmail]/Trash | |
*/ | |
function openInbox(cb) { | |
imap.openBox('[Gmail]/Drafts', true, cb); | |
} | |
imap.once('ready', function() { | |
openInbox(function(err, box) { | |
if (err) throw err; | |
imap.search([ ['X-GM-MSGID', '1486579858850663946'] ], function (err, results) { | |
if (err) { | |
console.log(err); | |
return; | |
} | |
var f = imap.fetch(results[0], { | |
request: { | |
headers: ['from', 'to', 'subject', 'date'], | |
bodies: 'HEADER.FIELDS (FROM TO SUBJECT DATE)', | |
struct: true | |
} | |
}); | |
f.on('message', function(msg, seqno) { | |
console.log('Message #%d', seqno); | |
var prefix = '(#' + seqno + ') '; | |
msg.on('body', function(stream, info) { | |
var buffer = ''; | |
stream.on('data', function(chunk) { | |
buffer += chunk.toString('utf8'); | |
}); | |
stream.once('end', function() { | |
console.log(prefix + 'Parsed header: %s', inspect(Imap.parseHeader(buffer))); | |
}); | |
}); | |
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(); | |
}); | |
}); | |
}); | |
}); | |
imap.connect(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment