Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build local node.js mail server

I have spent couple of days implementing my own mail server using node.js. I used modules like "smtp-server" for creating smtp server and also "smtp-connection" to connect and send mail to it. But I'm getting confused because I don't know how to send mails from my smtp server to providers smtp servers like google or yahoo.

Can anyone help me?

Here is my code for more information:

My index.js file:

var SMTPServer = require('smtp-server').SMTPServer;
var port = 9025;


var serverOptions = {
    name: "smtp-interceptor",
    onConnect: onConnect,
    onAuth: onAuth,
    onData: onData
};

var server = new SMTPServer(serverOptions);

server.listen(port, 'localhost', function () {
    console.log('SMTP server is listening on port ' + port);
});

function onConnect(session, callback) {
    console.log('Connected');
    return callback(); // Accept the connection
}

function onData(stream, session, callback) {
    stream.pipe(process.stdout); // print message to console
    console.log('Session \n', session.envelope);
    stream.on('end', callback);
}

function onAuth(auth, session, callback){
   if(auth.username !== 'Mahan' || auth.password !== 'Tafreshi') {
        return callback(new Error('Invalid username or password'));
   }
   callback(null, {user: 123}); // where 123 is the user id or similar property
}

And my connection.js file:

var SMTPConnection = require('smtp-connection');

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

var connection = new SMTPConnection({
    host: 'localhost',
    port: 9025,
    secure: false
});

connection.connect(function (){
    console.log('Connceted to SMTP server');
    var auth = {
        user: 'Mahan',
        pass: 'Tafreshi'
    };

    connection.login(auth, function (err) {
        if(err)
            return console.log('Login Failed \n', err);
        console.log('Login Successful');

        var envelope = {
            from: "[email protected]",
            to: "[email protected]"
        };

        var message = 'Test message1';

        connection.send(envelope, message, function (err, info) {
            if(err)
                return console.log('Error : ' + err);
            console.log('Message sent');
            console.log('Accepted  : ' + info.accepted);
            console.log('Rejected  : ' + info.rejected);
            console.log(info.response);

            connection.quit();
            console.log('Quit connection');
            connection.close();
        });
    });
});
like image 467
Mahan Avatar asked Sep 20 '16 19:09

Mahan


People also ask

Can I create my own SMTP server?

When it comes to building an SMTP server, there are a couple of routes that you can take. You can use a hosted SMTP relay service that provides scalable email relaying capabilities right out of the box. Or you can setup your own SMTP server, by building on top of an open source SMTP server solution.


1 Answers

There are many checks an email must pass before it's accepted by most mail providers. These checks attempt to validate the server sending the message is authorized to send on behalf of the sender.

IE: My server can send an email saying it's from "[email protected]"... That doesn't mean I'm "anywhere important" by any means.

While you may have had success sending mail from an SMTP server in the past using another technology such as PHP or an Exchange Server, the rules have changed significantly. Gmail has just began full enforcement this year.

I would assume your current issue has nothing to do with node as much as recent changes by the big providers.

Some of the checks that are needed include:

  • DKIM Keys (DNS Record)
  • SPF Record (DNS Record)
  • DMARK has been setup.
  • Dedicated IP Address for the server is required.
  • Your servers IP not being blacklisted.
  • The content of your email passes their filters.
  • Attempt to have an email sent from your server appear to be from a visitor or customer.
  • Among many others.

Any domain you want to "Act as Sender" must have these in place for most of the major providers to accept you message.


Google has a great set of tools and walkthroughs on getting an IP/Domain setup.

Visit the Google MX Record Checker and enter in the domain/subdomain you want to use as sender and it will tell you everything that is failing as well as passing.


Alternative Solutions

  • I use sendgrid.com. They have A node library that makes sending mail very easy. They also provide me the ability to proxy messages via SMTP. This means you can utilize the standard methods to deliver messages. You will just change out "localhost" with an hostname they provide. However, if this is for a new setup, go for the API.
  • Whomever is hosting your email should offer the ability for you send messages via SMTP or an API
  • An endless supply of other providers are out their, most of which allow low volume senders to send for FREE.

Word of warning

I tried for a few years keeping up with all the changes and inevitably, I continued to hit barriers of blocked messages with no ability to know until someone did not get an email. If your sending low volume, you should be able to use third parties without paying paying for it. If you are sending high volume, the cost of their service is cheap compared to the endless issues you will encounter even once you get it initially rolling.

PS. I have no affiliation with any email provider or sender. I pay them too.

like image 74
factorypolaris Avatar answered Sep 22 '22 08:09

factorypolaris