How to receive emails into your backend applications via webhooks (PHP/JS/API)
Tags: emailwebhook, emailapi, php, javascript
Published: 2024-01-20 22:35:26

## Into

Hi mates,

It's Alex, I'm the founder of ProxiedMail and since 2020 I've been building the system that helps you to keep your data secure with a top-notch proxy-email solution, but also it provides a great API to interact with emails.

Have you ever thought about receiving emails straight into your application? Sorry, forgot to say that it's free for very basic usage, but It will be enough for a small application.
Anyway, we always appreciate your support and are ready to give ours.

## Use cases

You could use it to display text on a big screen that visitors of your conference sent, in a photo printing machine, Zapier, or connect with the systems that don't provide an API other than an email message.
You can transmit the email signal that you sent somewhere to make the control easier or link the signals sent via emails to another system that supports webhooks.

The last case was used by a customer who came to us to set up an alarm arming/disarming system via email message. 
I don't know much of the details, but it sounds cool.
Just think about what kind of great apps you can build using this tool.

## Code examples

There a PHP and JS clients already built, but if you don't use those wonderful languages you can use pure API or just request a client for your language. 

### PHP ❤️ 

Let's start with my favorite language and it's PHP:

```php
<?php

use ProxiedMail\Client\Config\Config;
use ProxiedMail\Client\Entities\ResponseEntity\OauthAccessTokenEntity;
use ProxiedMail\Client\Entrypoint\PxdMailApinitializer;
use ProxiedMail\Client\Facades\ApiFacade;

require 'vendor/autoload.php';


// put here your ProxiedMail credentials
$email = 'example.com';
$pass = '1';

/**
 * @var ApiFacade $facade
 */
$facade = PxdMailApinitializer::init();
/**
 * @var OauthAccessTokenEntity $r
 */
$r = $facade->login($email, $pass);

//settings bearer token
$config = (new Config())->setBearerToken('Bearer ' . $r->getBearerToken());
$facade = PxdMailApinitializer::init($config);

//receiving API token by bearer token
$apiToken = $facade->getApiToken();

$config = new Config();

//setting API token
$config->setApiToken($apiToken->getApiToken());

$api = PxdMailApinitializer::init($config);

$wh = $api->createWebhook(); //creating webhook-receiver
$proxyEmail  = $api->createProxyEmail(
    [],
    null,
    $wh->getCallUrl() //specifying webhook URL
);



// while (true) with 100 seconds limit
foreach(range(0, 100) as $non) {
    echo "PROXY-EMAIL: " . $proxyEmail->getProxyAddress() . "\n";
    echo "Send the email to this proxy-email to get email payload printed here";
    
    //checking webhook receiver 
    $whStatus = $api->statusWebhook($wh->getId());

    echo "Webhook STATUS: \n";
    echo "Received: " . ($whStatus->isReceived() ? 'yes' : 'no') . "\n"; //printing webhook status

    //printing payload if received
    if ($whStatus->isReceived()) {
        echo "WEBHOOK PAYLOAD: \n";
        echo json_encode($whStatus->getPayload());
        break;
    }


    echo "\n";

    sleep(1);
}
```

Those codes create a proxy email address that is used to receive email messages and get them via built-in ProxiedMail callback. 
You can run the example on your machine and check it out.
Here's the potential result if you did everything in the right way:


```

PROXY-EMAIL: 4bd6c97b9@proxiedmail.com
Webhook STATUS: 
Received: no

PROXY-EMAIL: 4bd6c97b9@proxiedmail.com
Webhook STATUS: 
Received: no

PROXY-EMAIL: 4bd6c97b9@proxiedmail.com
Webhook STATUS: 
Received: yes
WEBHOOK PAYLOAD: 
{"id":"EB442408-D500-0000-00003CC8","payload":{"Content-Type":"multipart\/alternative; ...
```
JSON was cut to make this article shorter. Anyway, I have included the completed version for all API docs and clients.




We're continuously asking for our callback URL info if there is any callback was sent to it. 
Let's talk about built-in callback receivers further in this article.

### JS 

So, now we can dive deep into js. It's not as nice as PHP but still, some of you probably using it.

```js
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
                }
            }
        }
    );
}
```

JS code is a little bit longer as the client was generated via the OpenAPI generator, but still works fine. It also uses built-in webhook receivers.

## Features

As we have talked about the practical side you saw how to use its to use PM for your potential tasks let's talk about the features and specialities of API.

1. Built-in webhook receiver
As I mentioned previously it's a thing that allows you to create a special URL that will receive a callback for you.
Then, you will be able to continuously ask if there was something received via API. It's made to make our application work synchronously. Otherwise, we had to set up a server that was available for calls from outside, because proxy emails accept only callback URLs. 
2. Proxy-email
ProxiedMail was built to provide proxy email. You can go there and create endless proxy emails like pm1@proxiedmail.com, and pm2@proxiedmail.com and when you're using it the messages will be redirected to your real email OR|AND callback URL.
It's not the topic of the article, but it's not cool to use one email everywhere. Just for you to be on the same page with us.
3. Callback receiving UI
We're storing logs, so if you're not using built-in callback receivers you can check out the response of your API.
Also, even if you're using it you can still check out if the email webhook was delivered
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bfa2zet0nfk9gy5xyoz9.png)
4. Own domains
You can also attach your own domain to the system to create proxy emails like abc@myowndomain.com. So you will be able to receive webhook using your own domain.


That's quite a full list of what you should be aware about.

## Links to start from

ProxiedMail - https://proxiedmail.com/
PHP Client - https://github.com/proxied-mail/proxiedmail-php-client
JS Client - https://github.com/proxied-mail/proxiedmail-js-client
Docs - http://docs.proxiedmail.com/
Swagger - https://proxiedmail.com/api/v1/api-docs.yaml (just copy and paste it to the swagger editor)


## Conclusion 

In the end, you can use ProxiedMail to receive emails straight into your application with JS, PHP client, Rest API, or wait for the client of your favorite language.
Feel free to give us any kind of feedback.
Also, text me if any help is needed.