Integrate Mailgun in Ionic 3


#1

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 .


#2

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.


#3
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


#4

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