CORS error encountered using Mailgun API via Angular HttpClient

Angular 7 app faces a CORS error using Mailgun API with HttpClient. Revised code example provided. Should I change server config or adjust client code?

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class EmailDispatcher {
  constructor(private http: HttpClient) {}

  transmitEmail(): void {
    const headers = new HttpHeaders({
      'Authorization': 'Basic ' + 'api:YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY',
      'Content-Type': 'multipart/form-data'
    });

    const data = new FormData();
    data.append('from', 'alias <[email protected]>');
    data.append('to', '[email protected]');
    data.append('subject', 'Greetings');
    data.append('text', 'This email test adjusts CORS settings.');

    this.http.post('https://api.mailgun.net/v3/example.mailgun.org/messages', data, { headers })
      .subscribe(
        res => console.log('Response:', res),
        err => console.error('Error:', err)
      );
  }
}

hey, try using a node based proxy. i’ve been thru this and it fixd my cors issues. direct mailgun calls from client often result in these errors. maybe adjust your server too

hey, i solved mine by using a small aws lambda as a proxy. it fixed the cors problms and kept my api key secure without needing a full backend. try it out!

In my work with Angular and third-party APIs like Mailgun, I experienced a similar issue when directly calling the API from the client. The solution that worked best for me was implementing a server-side proxy using something like Express. This proxy securely relays requests between the client and Mailgun, which eliminates CORS concerns and avoids exposing sensitive API credentials. Though it does add another layer of complexity, this approach improved security and stability in our application, making sure that external calls were handled in a controlled environment.

In my experience, directly invoking Mailgun’s API from an Angular client inevitably leads to CORS-related difficulties. The problem arises because Mailgun does not supply the required CORS headers for client-side requests, which leaves the browser blocking the call. A solution that worked for me involved implementing a small backend endpoint to relay the request. This not only overcomes CORS restrictions but also protects your API credentials by keeping sensitive data on the server. Opting for a server-side solution may add complexity, but it provides a more secure, maintainable architecture.