I am using NodeJs together with imap, mailparser and bluebird to read the mail of my gmail account and finally write these to an Azure Database. But this is the first step for me to get a feeling how this works.
I use the code from Read email body with node js imap and alter the credentials.
when i execute the email.js script it returns the below error.
I hope you can help me out here.
Manny thanks,
Erik
ERROR
Connection error: Error: connect ECONNREFUSED 127.0.0.1:143
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1129:14)
email.js
var Imap = require("imap");
var MailParser = require("mailparser").MailParser;
var Promise = require("bluebird");
Promise.longStackTraces();
// Step 2: Declaring new imap object
var imapConfig = new Imap({
user: '[email protected]',
password: 'mypassword',
host: 'imap.gmail.com',
port: 993,
tls: true,
secure: true
});
var imap = new Imap(imapConfig);
Promise.promisifyAll(imap);
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
imap.once("ready", execute);
imap.once("error", function(err) {
console.error("Connection error: " + err.stack);
});
imap.connect();
function execute() {
imap.openBox("INBOX", false, function(err, mailBox) {
if (err) {
console.error(err);
return;
}
imap.search(["UNSEEN"], function(err, results) {
if(!results || !results.length){console.log("No unread mails");imap.end();return;}
var f = imap.fetch(results, { bodies: "" });
f.on("message", processMessage);
f.once("error", function(err) {
return Promise.reject(err);
});
f.once("end", function() {
console.log("Done fetching all unseen messages.");
imap.end();
});
});
});
}
function processMessage(msg, seqno) {
console.log("Processing msg #" + seqno);
// console.log(msg);
var parser = new MailParser();
parser.on("headers", function(headers) {
console.log("Header: " + JSON.stringify(headers));
});
parser.on('data', data => {
if (data.type === 'text') {
console.log(seqno);
console.log(data.text); /* data.html*/
}
});
msg.on("body", function(stream) {
stream.on("data", function(chunk) {
parser.write(chunk.toString("utf8"));
});
});
msg.once("end", function() {
// console.log("Finished msg #" + seqno);
parser.end();
});
}