DEV Community

Cover image for How to receive inbound email with NodeJS
Alex Yatsenko
Alex Yatsenko

Posted on • Edited on

How to receive inbound email with NodeJS

Hey,

I'm Alex, the individual behind ProxiedMail.
ProxiedMail elevates the email service by emphasizing privacy from the outset, encouraging the use of a distinct email for each interaction as an additional layer of security. This approach not only bolsters your email's privacy but also grants you enhanced management of your messages. Moreover, it facilitates a swift transition to alternative email services within moments. Our system is designed to enrich the email-based development experience further.

There are scenarios where directly receiving emails into an application is crucial. This need may arise from systems that lack an API but offer email alerts, or from a desire to incorporate user emails directly into your app's functionality. The possibilities for integrating email reception and processing within your applications are vast. In this guide, I'll detail how to accomplish this using NodeJS.

How it works

With ProxiedMail, you can choose your own email address or get one automatically. Usually, we send emails to your conventional email, like Gmail or ProtonMail.
It works like this: an email sent to abc@proxiedmail.com goes to blabla@protonmail.com.
If you set up a webhook email, we'll send a webhook to that email. If you don't want emails forwarded to your regular email, you can use a special internal address, such as *@proxiedmail-int.int (for example, testingadw@proxiedmail-int.int).

API Features

  1. Creating endless proxy emails with one of ProxiedMail domains (i.e abc@proxiedmail.com, abcd@pxdmail.com, abcde@pxdmail.net)
  2. Setting up forwarding email or disabling forwarding
  3. Setting up a callback to your URL
  4. Browsing received emails on the received emails endpoint
  5. Setting up custom domains. You can do everything using your domain as well.
  6. Domain-to-domain forwarding. Just in case you need it we can forward emails by mask, like *@domainhostedatproxiedmail.com -> *someotherdomain.com. In this case, the MX of the first domain should be pointed to ProxiedMail and the second domain should be verified by TXT record.

Let's start

Follow this easy instruction to start receiving emails into your application.

  1. Sign up on ProxiedMail
  2. Create your API Key
  3. Install the npm package into your application.

npm install proxiedmail-api

Start coding/webhook implementation.

Let's say we've created t.js file with the following contents:

*If you got your API key you can hardcode it into the application. *

let ProxiedMailApi = require('proxiedmail-api');

let apiInstance = new ProxiedMailApi.UserApi();


let authReq = {
    'authRequest': ProxiedMailApi.AuthRequest.constructFromObject(
        {
            "data": {
                "type": "auth-request",
                "attributes": {
                    "username": "example@example.com", //please pass your credentials here after sign up
                    "password": "example"
                }
            }
        }
    )
};

//logging in
apiInstance.userAuth(authReq, (error, data, response) => {
    if (error) {
        console.error("error:" + error);
    } else {
        let token = data.data.attributes.token;
        var apiApiClient = new ProxiedMailApi.ApiApi();
        apiApiClient.apiClient.authentications['api_auth'].accessToken = token; //settings bearer token

        //getting api token
        // your can skip this step and get one on the UI https://proxiedmail.com/en/settings
        apiApiClient.apiV1ApiTokenGet((error, data, response) => {
            if (error) {
                console.error("error:" + error);
            }

            //settings up api token
            let apiToken = data.token;
            var callbackApi = new ProxiedMailApi.CallbackApi();
            callbackApi.apiClient.authentications['api_key'].apiKey = apiToken;

            // creating built-in callback-receiver
            callbackApi.addCallback((error, cb, response) => {
                const proxyBindingPayload = {'proxyBindingCreate': createProxyBindingPayload(cb.call_url)}

                var proxyBindingApi = new ProxiedMailApi.ProxyBindingApi();
                //creating proxy-email and assigning callback url
                proxyBindingApi.addProxyBinding(proxyBindingPayload, (error, pb, response) => {

                    //continuously checking callback status to get the email
                    //just send the email to pb.data.attributes.proxy_address to check it out
                    const interval = setInterval(function () {
                        callbackApi.apiV1CallbackGetHashGet(cb.id, function (error, cbInfo) {
                            console.log('check callback. email: ' + pb.data.attributes.proxy_address);
                            console.log(cbInfo)

                            //printing email info about callback
                            if (cbInfo.is_received) {

                                console.log('received')
                                console.log(cbInfo)
                                console.log('Subject: ' + cbInfo.payload.payload.Subject)
                                console.log('Message: ' + cbInfo.payload.payload['body-plain'])
                                console.log('From: ' + cbInfo.payload.payload['from'])

                                clearInterval(interval);
                            }

                        });
                    }, 2000);
                });
            } )

        });
    }
});


//callback construction function
function createProxyBindingPayload(callbackUrl) {
    return ProxiedMailApi.ProxyBindingCreate.constructFromObject(
        {
            "data":{
                "type":"proxy_bindings",
                "attributes":{
                    "real_addresses":[], //on empty it will generate internal real address
                    //that kind of real addresses is not forwarding anything to any email
                    //however if you need forwarding just use something like "abc@example.com"
                    //please note that real address should be confirmed
                    "proxy_address": null,
                    "callback_url": callbackUrl
                }
            }
        }
    );
}
Enter fullscreen mode Exit fullscreen mode

Also if you prefer you can use it without callback if you want the ability to catch more than one email:

let ProxiedMailApi = require('proxiedmail-api');

let apiInstance = new ProxiedMailApi.UserApi();


let authReq = {
    'authRequest': ProxiedMailApi.AuthRequest.constructFromObject(
        {
            "data": {
                "type": "auth-request",
                "attributes": {
                    "username": "example.com", //please pass your credentials here after sign up
                    "password": "1"
                }
            }
        }
    )
};

//logging in
apiInstance.userAuth(authReq, (error, data, response) => {
    if (error) {
        console.error("error:" + error);
    } else {
        let token = data.data.attributes.token;
        var apiApiClient = new ProxiedMailApi.ApiApi();
        apiApiClient.apiClient.authentications['api_auth'].accessToken = token; //settings bearer token

        //getting api token
        // your can skip this step and get one on the UI https://proxiedmail.com/en/settings
        apiApiClient.apiV1ApiTokenGet((error, data, response) => {
            if (error) {
                console.error("error:" + error);
            }

            //settings up api token
            let apiToken = data.token;
            var callbackApi = new ProxiedMailApi.CallbackApi();
            callbackApi.apiClient.authentications['api_key'].apiKey = apiToken;

            // creating built-in callback-receiver
            callbackApi.addCallback((error, cb, response) => {
                const proxyBindingPayload = {'proxyBindingCreate': createProxyBindingPayload(cb.call_url)}

                var proxyBindingApi = new ProxiedMailApi.ProxyBindingApi();
                //creating proxy-email and assigning callback url
                proxyBindingApi.addProxyBinding(proxyBindingPayload, (error, pb, response) => {

                    //continuously checking callback status to get the email
                    //just send the email to pb.data.attributes.proxy_address to check it out
                    const interval = setInterval(function () {


                        const proxyBinding = response;

                        var receivedEmailApi = new ProxiedMailApi.ReceivedEmailApi();
                        receivedEmailApi.apiV1ReceivedEmailsLinksProxyBindingIdGet(
                            response.body.data.id,
                            function (error, pb, response) {

                                console.log("Checking inbox of: " + proxyBinding.body.data.attributes.proxy_address)


                                console.log('LIST OF EMAILS', response.body)
                                for (let i in response.body.data) {

                                    receivedEmailApi.apiV1ReceivedEmailsReceivedEmailIdGet(
                                        response.body.data[i]['id'],
                                        function (error, pb, response) {
                                            console.log(
                                                "RECEIVED EMAIL \n",
                                                response.body
                                            )
                                        }
                                    )
                                }

                            }
                        )

                    }, 2000);
                });
            } )

        });
    }
});


//callback construction function
function createProxyBindingPayload(callbackUrl) {
    return ProxiedMailApi.ProxyBindingCreate.constructFromObject(
        {
            "data":{
                "type":"proxy_bindings",
                "attributes":{
                    "real_addresses":[
                        "dawwaawdawd@proxiedmail-int.int"
                    ],
                    "proxy_address": null,
                    "callback_url": callbackUrl,
                    "is_browsable": true,
                }
            }
        }
    );
}
Enter fullscreen mode Exit fullscreen mode

Payload example

All of our examples contain a payload. Example of email payload:

{
   "id":"EB442408-D500-0000-00003CC8",
   "payload":{
      "Content-Type":"multipart\/alternative; boundary=\"000000000000714564060f56f6c2\"",
      "Date":"Sat, 20 Jan 2024 02:00:25 +0000",
      "Dkim-Signature":"DKIM",
      "From":"Alex Yatsenko <sender@gmail.com>",
      "Message-Id":"<CAJj9C9dVhSJZDwRDM-H=vhzPttpg253biEvabFtEHiS4wriK8A@mail.gmail.com>",
      "Mime-Version":"1.0",
      "Received":"by mail-wm1-f44.google.com with SMTP id 5b1f17b1804b1-40e9ffab5f2so10064475e9.1 for <4bd6c97b9@proxiedmail.com>; Fri, 19 Jan 2024 18:00:38 -0800 (PST)",
      "Subject":"hey mate",
      "To":"4bd6c97b9@proxiedmail.com",
      "X-Envelope-From":"sender@gmail.com",
      "X-Mailgun-Incoming":"Yes",
      "X-Received":"Received details",
      "body-html":"<div dir=\"ltr\">hey hey<\/div>\r\n",
      "body-plain":"hey hey\r\n",
      "domain":"proxiedmail.com",
      "from":"Alex Alex <sender@gmail.com>",
      "message-headers":"HEADERS JSON....",
      "recipient":"4bd6c97b9@proxiedmail.com",
      "sender":"sender@gmail.com",
      "signature":"....",
      "stripped-html":"<div dir=\"ltr\">hey hey<\/div>\n",
      "stripped-text":"hey hey",
      "subject":"hey mate",
      "timestamp":"1705716046",
      "token":"..."
   },
   "attachments":[

   ],
   "recipient":{
      "address":"4bd6c97b9@proxiedmail.com"
   },
   "receivedAt":"Sat Jan 20 2024 02:00:46 GMT+0000",
   "user":{
      "id":"1B3AAA43-11-0000-cc",
      "username":"username+t1@gmail.com",
      "token":"Bearer ...."
   }
}
Enter fullscreen mode Exit fullscreen mode

Summary

Summarizing our information you can use both ways to receive emails: via callback and also using browsing emails.
The payload contains all of the information about email and attachments.

If you have any questions please contact devjs@pxdmail.com.
Feel free to check out the documentation as well.

Feel free to check out or contribute on Github.
Also, you can check out the article about receiving emails in the best language (PHP).

Top comments (0)