Integrate Mailgun in Ionic 3

I want to send email without using email composer so I checked this tutorial (that don’t work) and this github repo for the integration of Ionic with Mailgun…
I’ve also checked this question on stackoverflow and I think that my code it’s the same but I’m not able to make it work on my Ionic App.

This is my code:

import { HttpClient, HttpHeaders } from '@angular/common/http';
import {Http, Request, RequestMethod} from "@angular/http";
...
        
export class HomePage {
 ...
 mailgunUrl: string;
 mailgunApiKey: string;
 ...
        
 constructor(
 ...
   public  http: HttpClient,
 ) {
      this.http = http;
      this.mailgunUrl = "mydomain";
      this.mailgunApiKey = window.btoa("api:key...");
     });
  }
  .....

   send(recipient: string, subject: string, message: string) {
            this.http.post("https://api.mailgun.net/v3/" + this.mailgunUrl + "/messages", "from=test@mail.it&to=" + recipient + "&subject=" + subject + "&text=" + message,
          {
            headers: { 'Authorization': 'Basic ' + this.mailgunApiKey, "Content-Type": "application/x-www-form-urlencoded" },
          }).subscribe(success => {
            console.log("SUCCESS -> " + JSON.stringify(success));
          }, error => {
            console.log("ERROR -> " + JSON.stringify(error));
          });
      }
...

On Postman it works perfectly, but not in my application, that gives me this error:
enter image description here

Where is the problem? I’m not able to understand it…I’m stuck from yesterday on this problem .

I had a similar problem, and I was facing CORS issues.
You can use this plugin https://ionicframework.com/docs/native/http/ instead of http from @angular/http.
The only drawback is that it will only work on device.

import { HTTP } from '@ionic-native/http';

  constructor(
    public cordovaHttp: HTTP
  )


  send(subject: string, message: string) {
    let headers = {
      'Authorization': 'Basic ' + this.mailgunApiKey,
      'Content-Type': 'application/x-www-form-urlencoded'
    }

    let body = {
      from: test@email.com,
      to: 'test2@email.com',
      subject: subject,
      text: message
    }

    let url = 'https://api.mailgun.net/v3/' + this.mailgunUrl + '/messages';

    return this.cordovaHttp.post(url, body, headers);
  }

This code works for me

thank you so so much! Using native http works for me also! thank you so so much, you saved my day!

1 Like

Hello i have a question, i use your code but i got an error in the Constructor:

public cordovaHttp: HTTP,

the “HTTP” is red underline , i dont know why. I installed the plugin correctly and put the import line:
import { HTTP } from ‘@ionic-native/http’; the red underline is just in the constructor, like i mentioned before.

when i put the mouse over it says: [ts] Cannot find name ‘HTTP’. [2304]

any idea? thanks