Permit logo
Home/Blog/

Send Emails via Mailgun’s API directly from the browser

Learn how to send Emails with the Mailgun API directly from the browser using Frontend Only Authorization (FoAz) - A backendless communication solution.
Send Emails via Mailgun’s API directly from the browser
Shuvy Ankor

Shuvy Ankor

|
  • Share:

With the evolution of frontend development and the advent of backendless tools, frontend developers now possess significant power to build complete applications without relying on backend code. However, one area that often necessitates backend involvement is enforcing access control for backend-oriented APIs. This is due to the requirement of authenticating these APIs with a secret key that cannot be exposed on the frontend. But there is a solution!

In this article, we'll examine how to utilize Frontend Only Authorization (FoAz) - a new open standard to use Mailgun’s API directly from the frontend. This will allow us to designate specific users who can send emails with Mailgun without the need for any backend setup.

Granting the right permissions for sending emails with the use of Mailgun can be a challenge. The integration of Mailgun with FoAz will allow us to directly utilize Mailgun’s API and add an authorization layer on top of it, eliminating the need for time-consuming server modifications or developer involvement.

What is Frontend Only Authorization (FoAz)

FoAz accepts API calls, verifies identity, checks for permissions, and adds secrets - allowing secure use of APIs with granular permissions directly from the frontend. In this case, FoAz will verify the user's frontend JWT token, check if they have proper permissions to perform the API call, and then forward the call to the backend API.

foaz_diagram.png

By using FoAz, we can authenticate our users in the frontend, and then use the same JWT token to authorize them to perform API calls.

Why Use Mailgun with FoAz:

Integrating Mailgun with Foaz allows users (in our example, marketing managers) to gain direct authorization to send emails. Administrators can define access rules using Permit.io, granting permission to authorized personnel. This simplifies the process and eliminates the need for server modifications or developer involvement.

Example scenario: Sending e-commerce discount coupon codes 

Our example is set in an e-commerce store with a sales department. Customers often request discount coupons, which can be created by sales department employees. However, only the sales manager has the authority to send an email to the user with the coupon. 

While we want to create a UI for sending emails, we would also like to keep the permissions model we have on the server side for our users. Having all the permissions streamlined and managed by Permit.io, and the email-sending being handled by the Mailgun service, we’ve got a comprehensive solution that combines the best of both worlds. This combination allows us to grant exclusive email-sending privileges to the sales manager, saving time and ensuring proper access control.

Let’s see how it’s done.

1. Sign up to Mailgun

1.png

If you have signed up for Mailgun's service, you can click on login and connect. If not, sign up for the service now.

2. Find your API key

To send an email with Mailgun we need to send a post request with a private API key. To get those, click Overview:

12.png


2.png

Now that we have a private API key and we know how to create an API request, we will connect to Permit.

3. Sign up to Permit

Go to app.permit.io 
If you are not registered, please register; it's really easy. After onboarding or logging in, we need to define our users and assign them authorization policies. 

4. Setup some basic application-level roles and resources 

  • Define roles:

    For the purpose of this tutorial, we will create 2 roles: 
    a role designated for the Head of Sales, titled “sales_sdmin,” and a second role designated for the Sales Representatives, titled “salesperson”.  

    To create new roles, go to the Policy screen, Click Roles, and Add Role

    Note:

    In this example, we have translated our organization-level roles into application-level roles. This will be done differently for every application, and it is up to you to decide how this role translation should be done. To learn more about planning role-based access control (RBAC) for your application, check out this blog

    4.png

    With our roles defined, let’s define some resources

  • Define Resources:

    In the Policy screen, Click Resources, and Create a Resource

    Create a resource named “coupon”. 

    Each resource has actions that can be performed on it. For the purpose of this tutorial, we will be adding a “share” action, and, in the next step, restrict it to the “sales_admin” role. 

    You can, of course, create additional actions (Such as “create”, “edit”, “view,” or anything else applicable in your use-case) and assign them to other roles, as can be seen in the screenshot:

    10.png

  • Define a Policy 

    Now that we have a UserResource, and Action, it’s time to create an authorization policy. 

    Go to the Policy screen, to set your sales_admin to be able to share a coupon. It’s as easy as checking a checkbox 🙂

    11.png


    In the screenshot, you can see the sales_admin can create, edit, share and view a coupon, while a salesperson can only view it. 

5. Set up FoAz

Now that we have basic RBAC setup, it is time to connect Permit to Mailgun through FoAz:

  • Go to the FoAz Proxy screen. 

  • If you receive the following prompt:

    “There are no JWKs configured to this environment. In order to enable FoAz you need to make sure you have JWKs configured”. 

    9.png

    Click “JWKS configured”, and add the relevant configuration for your JWKs per environment and project. Learn more about JWKs here.

    8.png
  • Fill out the FoAz form in the following order:
    Proxy Name
    Proxy Request URL
    - Fill in Mailgun’s base API URL
    HTTP method - select POST
    Resource - select “coupon”
    Action - select “share”
    Secret configuration - Under “Authentication Mechanism” select Basic, under User write “API”, and in Password fill in your MailGun API key.

    7.png
  • Click “Create” in the top right corner.
  • Once the form is full and saved, click “Example Code <>” in the top right corner
1.png

6. Create a request

5.png

To create your proxy request based on the example code:

  • Replace HTTP_METHOD with POST

  • In USER_JWT add the token compatible with the defined JWKs

  • In PROXIED_URL, copy the API base URL from Mailgun.

    This is a basic example of using FoAz, but we need to provide additional information in both the body and the header of the request. This information includes details like the sender's name, the email subject, and more.

    This code is a sample JavaScript code that you can integrate into your front-end application. Its purpose is to send an email containing a coupon code by utilizing the integration between FOAZ and Mailgun:

  • const sendCoupon = () => {
        const myHeaders = { Authorization: TOKEN };
       
        const formData = new FormData();
        formData.append(
          'from',
          'Excited User <mailgun@ggggbbbb.org>'
        );
        formData.append('to', 'exppp@gmail.com');
        formData.append('subject', 'Hello Permit');
        formData.append('text', 'Coupon= 1234556');
       
        fetch(`https://proxy.api.permit.io/proxy/${FOAZ_ID}?url=${URL_MAILGUN}`, {
          method: 'POST',
          headers: myHeaders,
          body: formData,
          redirect: 'follow',
        })
          .then((response) => response.text())
          .then((result) => console.log(result))
          .catch((error) => console.log('error', error));
       };

Conclusion

In this article, we discovered the simplicity of connecting our frontend application directly to Mailgan in a secure manner, with the added benefit of user-based permissions, all thanks to FoAz. This approach has allowed us to save valuable time in server development and significantly expedite our development process within the company.

FoAz is not limited to Email sending. You can use FoAz to access any API that requires authentication, and you can use it to build a complete application without any backend code. 

Want to stay in touch and contribute to the revolution of frontend development? Join our community.

Written by

Shuvy Ankor

Shuvy Ankor

Full-stack Core Team Developer@ Permit.io

Test in minutes, go to prod in days.

Get Started Now

Join our Community

2026 Members

Get support from our experts, Learn from fellow devs

Join Permit's Slack