dmx
dmx

Reputation: 1990

Angular 6 http: How to send mail with mailgun API using angular 6

I want to send mail to user from angular 6 front-end. I want to use mailgun api to do this. Here is an example with curl that is working find and I want to "translate" this into angular 6 http:

curl -s --user 
'api:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'  
https://api.mailgun.net/v3/sandbox5xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.mailgun.og/messages  
-F from='Mailgun Sandbox <[email protected]>'  
-F to='Big boss <[email protected]>'  
-F subject='Hello mdx'  
-F text='This is cool !'

I have tried this :

 sendMail(form) {
    this.http
      .post(
        'https://api.mailgun.net/v3/sandboxxxxxxxxxxxxxxxxxxxxxxxx.mailgun.og/messages',

          {
            'from': 'Mailgun Sandbox <[email protected]>',
            'to': '[email protected]',
            'subject': 'Hello',
            'text': 'This is cool !'
          }

      )
      .subscribe(
        res => {
          console.log('res : ', res);
        },
        err => {
          console.log('err : ', err);
        }
      );
  }

When I click on send, I got this error: enter image description here

Any idea on how to write this curl into angular ?

Upvotes: 0

Views: 1266

Answers (2)

Sam Herrmann
Sam Herrmann

Reputation: 6986

Based on your curl example in which you use the -F flag, mailgun is expecting multipart Post data. Your Angular attempt simply sends the data as a JSON object, which is not the same. Instead create a FormData object, add your data in there, then POST your FormData object.

Upvotes: 0

Alexander Staroselsky
Alexander Staroselsky

Reputation: 38827

Try the following using FormData to the create the multipart/form-data and using a Basic Authorization header for the username/password --user authentication:

import { HttpHeaders } from '@angular/common/http';

// ...

const headers = new HttpHeaders({
  'enctype': 'multipart/form-data',
  'Authorization': `Basic ${btoa('api:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')}`
});

const formData = new FormData();
formData.append('from', 'Mailgun Sandbox <[email protected]>')
formData.append('to', '[email protected]');
formData.append('subject', 'Hello');
formData.append('text', 'This is cool !');

sendMail(form) {
  this.http
    .post(
      'https://api.mailgun.net/v3/sandboxxxxxxxxxxxxxxxxxxxxxxxx.mailgun.og/messages',
      formData, 
      { headers }
    ).subscribe(
      res => { console.log('res : ', res); },
      err => { console.log('err : ', err); }
    );
}

You may be able to get with not using enctype or Content-Type request headers.

Hopefully that helps!

Upvotes: 2

Related Questions