Mailgun in Ionic - CORS issues on iOS device?

Hey everyone,

I’m running into an issue trying to use Mailgun in my Ionic 3 app. When I run the function to send mail in the browser, I have a Chrome plugin that allows me to enable CORS and it can send the message just fine. However, in my app on my device, when I try to send an email, I get an error:

{ "body": { "isTrusted": true}, "status": 0, "ok": false, {}, "type": 3"url": null}

I believe this is related to CORS.

I even tried adding this line to my index.html file but all it did was cause all sorts of errors with trying to talk to my REST API:

<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">

Here is the relevant code for the function that sends the email:

send(recipient: string, subject: string, message) {
      var requestHeaders = new Headers();
      requestHeaders.append("Authorization", "Basic " + this.mailgunApiKey);
      requestHeaders.append("Content-Type", "application/x-www-form-urlencoded");
      return this.http.request(new Request({
          method: RequestMethod.Post,
          url: `${this.mailgunUrl}/messages`,
          body: "from=bugs@bandly.com&to=" + recipient + "&subject=" + subject + "&text=" + message,
          headers: requestHeaders
      }));
    }

Does anyone have any insight into what I could missing here?

Are you in deploy or --prod mode? This is normal if you can in browser (ionic serve) because it deletes the CORS for testing purposes. Have a look on the forum with CORS keyword for more information.

Hm an interesting question. I run ionic cordova build ios when I’m testing because adding the --prod flag adds so much extra time. Maybe I should try it with it to see if that solves the problem?

UPDATE: Alright, so I tried this with the --prod flag and I’m still running into that same error. I couldn’t quite find anything useful about CORS on the ionic forum. Is there anything in particular you might be able to point me to?

CORS is an error raised because you’re trying to use a domain or subdomain (DNS) you have no permission for. It’s meant to prevent hackers to use something or server they are not allowed to use (cross domain hack).

iOS is very strict about that, more than Android. Anyways, you’ll still have the issue as long as you’re trying to send an email from an unregistered / unauthorized domain in a real production app.
For the rest, you can disable CORS policy for testing, there is a fix for iOS somewhere in forums.

This official post on blog
http://blog.ionic.io/handling-cors-issues-in-ionic/

Also here

1 Like

Thankyou very much for this information. I actually think I have an alternative option than sending an email and running into this CORS request. I’ll go with that for now.

Thanks!

Glad it helped, snstarosciak. By the way, we talked about mailgun, but this also worth with any external API, rest, or webservice call.

I have the same issue with mailgun and CORS. How did you solve it?

1 Like

Hi’, how did you solve it?

Hi @fdambrosio i’ve resolved with this steps

for first time

install HTTP native plugin from IONIC NATIVE and
import { HTTP } from '@ionic-native/http';

declare this variable

    var url = "https://api.mailgun.net/v3/" + this.mailgunUrl + "/messages";
    let body = {
      "from": 'xxx@xxx.it',
      "to": 'xxx@xxx.com',
      "subject": "XXX " + formData.subject,
      "html": "<html><body>First Name: " + formData.firstName + "<br>" + "Last Name: " + formData.lastName + "<br>" + "Email: " + formData.email + "<br>" + "Subject: " + formData.subject + "<br><br>" + "Message: " + formData.message + "</body></html>"
    }
    let headers = {
      "Authorization": "Basic " + this.mailgunApiKey,
      "Content-Type": "application/x-www-form-urlencoded"

    };

and the last step is

this.http2.post(url, body, headers).then(data => {
      this.loading.dismiss();

      let alert = this.alertCtrl.create({
        title: 'Email Inviata',
        message: 'Grazie per averci contattato. Le risponderemo appena possibile',
        buttons: [
          {
            text: 'OK',
            role: 'cancel',
            handler: () => {
              console.log('Cancel clicked');
            }
          }
        ]
      });
      alert.present();
    })
      .catch(error => {
        this.loading.dismiss();

        let alert = this.alertCtrl.create({
          title: 'Errore',
          message: 'Si è verificato un errore durante la trasmissione dei dati. Si prega di riprovare!',
          buttons: [
            {
              text: 'OK',
              role: 'cancel',
              handler: () => {
                console.log('Cancel clicked');
              }
            }
          ]
        });
        alert.present();
      });

if you want I can past all code of my .ts page :slight_smile:

2 Likes

thanks! with HTTP native plugin there’s no CORS problem.

Can you show me your *.ts file ! thanks in advance