Sometimes, we want to receive email in Node.js.
In this article, we’ll look at how to receive email in Node.js.
How to receive email in Node.js?
To receive email in Node.js, we can use the node-imap
package.
To install it, we run
npm install imap
Then we use it by writing
const Imap = require("imap");
const { inspect } = require("util");
const imap = new Imap({
user: "mygmailname@gmail.com",
password: "mygmailpassword",
host: "imap.gmail.com",
port: 993,
tls: true,
});
const openInbox = (cb) => {
imap.openBox("INBOX", true, cb);
};
imap.once("ready", () => {
openInbox(function (err, box) {
if (err) throw err;
const f = imap.seq.fetch("1:3", {
bodies: "HEADER.FIELDS (FROM TO SUBJECT DATE)",
struct: true,
});
f.on("message", (msg, seqno) => {
console.log("Message #%d", seqno);
const prefix = "(#" + seqno + ") ";
msg.on("body", (stream, info) => {
let buffer = "";
stream.on("data", (chunk) => {
buffer += chunk.toString("utf8");
});
stream.once("end", () => {
console.log(
prefix + "Parsed header: %s",
inspect(Imap.parseHeader(buffer))
);
});
});
msg.once("attributes", (attrs) => {
console.log(prefix + "Attributes: %s", inspect(attrs, false, 8));
});
msg.once("end", () => {
console.log(prefix + "Finished");
});
});
f.once("error", (err) => {
console.log("Fetch error: " + err);
});
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();
to receive email via IMAP.
We create an IMAP
instance with the credentials for the email server.
Then we listen to the ready
event with imap.onace
.
In it, we call imap.seq.fetch
to fetch the emails.
And then we call f.on
with 'message'
and the callback that gets the messages from a stream.
We received everything when the end
event is received, which we listen to by calling msg.once
with 'end'
and the event handler callback.
And we call imap.connect()
to make the connection to the IMAP server.
Conclusion
To receive email in Node.js, we can use the node-imap
package.