I have this code to save email using draft
module.exports.saveDraftMessage = async (req, res, next) => {
try {
const imap = new Imap(imapConfig);
imap.once('ready', () => { imap.openBox('Drafts', false, (err, box) => {
if (err) throw err;
let str = "to:" + '[email protected]' + " subject:" + 'Test Draft Mail' + " body: " + 'This is Draft Mail' + " text: " + 'Draft Mail Body';
imap.append(str);
})
});
imap.once("error", err => {
console.error("IMAP connection error:", err);
if (err)
res.status(500).json({ error: "An error occurred.", });
imap.end();
});
if (imap.state == 'disconnected') {
imap.connect();
}
}
catch (error) {
console.log("error ==> ", error)
res.status(500).json({ error: "An error occurred.", });
}
}
when i execute this method error is not there but while fetching Drafts mail it is not retrieved.
fetch method:
module.exports.getDraftMessage = async (req, res, next) => {
try {
const imap = new Imap(imapConfig);
imap.on("ready", () => {
imap.openBox("Drafts", true, (error, box) => {
if (error) throw error;
console.log('Connected!')
imap.search(['ALL', ['SUBJECT', 'Test Draft Mail']], function (err, results) {
if (err){
console.log('failed to search the mail.');
} else {
if (!results || !results.length){
console.log('no mails!!!');
imap.end();
} else {
var f = imap.fetch(results, {bodies:''});
f.on('message', function (msg, seqno) {
msg.on('body', function (stream, info) {
simpleParser(stream, function (err, mail) {
console.log(mail.from);
console.log('==================');
console.log(mail.subject);
console.log('==================');
console.log(mail.date);
})
});
msg.once('end', function() {
console.log(seqno + 'finished.');
});
});
f.once('error', function(err) {
console.log('failed to fetch: ' + err);
});
f.once('end', function() {
console.log('succeed in getting all mails!');
imap.end();
});
}
}
})
imap.on("mail", () => {
console.log("New one!")
})
});
});
if (imap.state == 'disconnected') {
imap.connect();
}
}
catch (error) {
console.log("error ==> ", error)
res.status(500).json({ error: "An error occurred while fetching mails.", });
}
}
Any solution Thanks