How to Send Emails via Mailgun Using JavaScript

I’m working on a JavaScript project where I need to send emails using the Mailgun API, but I’m confused about how to properly include authentication. I wrote a sample snippet below, yet I’m not sure where my API key should be inserted or how to format the header to make the authentication work. I would appreciate detailed guidance on placing the API key in the request so that the call is correctly authorized and executed. Here is an updated example:

const initiateEmail = () => {
  const requestDetails = {
    method: 'POST',
    url: 'https://api.mailgun.net/v3/yourSandboxDomain/messages',
    headers: {
      'Authorization': 'Basic ' + btoa('api:YOUR_NEW_API_KEY')
    },
    data: {
      from: 'Mailgun Tester <postmaster@yourSandboxDomain>',
      to: 'Receiver <[email protected]>',
      subject: 'Test Email',
      text: 'This email serves as a test for sending messages through the Mailgun API using JavaScript.'
    }
  };
  executeRequest(requestDetails);
};

initiateEmail();

Any advice on ensuring that the authentication details are correctly applied would be highly helpful.

Based on my experience working with Mailgun, ensure that the API key is correctly embedded in the Authorization header as a Base64 encoded string. The typical approach is to use ‘api:’ concatenated with your API key, then encoding it using something like btoa in JavaScript. However, it is important to note that exposing your API key in client-side code is not secure. For production use, I recommend moving the email sending logic to server-side code to secure your credentials and avoid misuse.

hey, so using client side js works, but its kinda risky. you can send the header with btoa(‘api:YOUR_KEY’), however, best to route through a backend to hide your credintials. trust me, it saves you from potential exploits.