What is smtp-server?
The smtp-server npm package is a simple and powerful SMTP server library for Node.js. It allows you to create custom SMTP servers for receiving and processing emails. This package is useful for testing email sending functionality, building email processing systems, and more.
What are smtp-server's main functionalities?
Basic SMTP Server
This code sets up a basic SMTP server that listens on port 25. It prints incoming email messages to the console.
const SMTPServer = require('smtp-server').SMTPServer;
const server = new SMTPServer({
onData(stream, session, callback) {
stream.pipe(process.stdout); // Print message to console
stream.on('end', callback);
}
});
server.listen(25, () => {
console.log('SMTP server is listening on port 25');
});
Authentication
This code sets up an SMTP server with basic authentication. It checks the username and password provided by the client.
const SMTPServer = require('smtp-server').SMTPServer;
const server = new SMTPServer({
onAuth(auth, session, callback) {
if (auth.username === 'user' && auth.password === 'pass') {
callback(null, { user: 'user' });
} else {
callback(new Error('Invalid username or password'));
}
}
});
server.listen(25, () => {
console.log('SMTP server with authentication is listening on port 25');
});
Custom Message Handling
This code sets up an SMTP server that parses incoming email messages and logs the subject and text content to the console.
const SMTPServer = require('smtp-server').SMTPServer;
const simpleParser = require('mailparser').simpleParser;
const server = new SMTPServer({
onData(stream, session, callback) {
simpleParser(stream, (err, parsed) => {
if (err) {
callback(err);
} else {
console.log('Subject:', parsed.subject);
console.log('Text:', parsed.text);
callback();
}
});
}
});
server.listen(25, () => {
console.log('SMTP server with custom message handling is listening on port 25');
});
Other packages similar to smtp-server
nodemailer
Nodemailer is a module for Node.js applications to allow easy email sending. While smtp-server focuses on receiving and processing emails, Nodemailer is designed for sending emails. It supports various transport methods, including SMTP, and is widely used for its simplicity and flexibility.
maildev
MailDev is a simple way to test your project's generated emails during development. It acts as an SMTP server and a web interface to view and inspect emails. Unlike smtp-server, which is a library for creating custom SMTP servers, MailDev is a complete tool with a built-in web interface for email inspection.
smtp-protocol
smtp-protocol is a low-level SMTP protocol library for Node.js. It allows you to create custom SMTP clients and servers. While smtp-server provides a higher-level API for creating SMTP servers, smtp-protocol offers more granular control over the SMTP protocol, making it suitable for advanced use cases.