Angular 2:在Ionic 2中使用Mailgun发送电子邮件

时间:2017-09-05 13:17:52

标签: angular ionic2 mailgun

我正在尝试使用Angular 2中的Mailgun向我的应用程序实现电子邮件通知。但是当我执行send()函数时,我收到控制台错误。我不知道怎么解决,希望你能事先帮助我。这是我的代码:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Http, Headers, RequestOptions } from "@angular/http";
import "rxjs/Rx";

import { TabsPage } from '../tabs/tabs';

@IonicPage()
@Component({
  selector: 'page-confirmorder',
  templateUrl: 'confirmorder.html',
})
export class ConfirmorderPage {

  recipient: string = "sampleemail@gmail.com";
  subject: string = "FirstTesting";
  message: string = "Hello, this is just a drill.";
  mailgunUrl: string = "<--My Domain-->";
  apiKey: string = "<--My API Key-->";

    tabBarElement: any;

  constructor(public http: Http, public navCtrl: NavController, public navParams: NavParams) {

  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad ConfirmorderPage');
  }

  send() {
        if(this.recipient && this.subject && this.message) {
            let headers = new Headers(
                {
                    "Content-Type": "application/x-www-form-urlencoded",
                    "Authorization": "Basic " + this.apiKey
                }
            );
            let options = new RequestOptions({ headers: headers });
            let body = "from=email@sample.com&to=" + this.recipient + "&subject=" + this.subject + "&text=" + this.message;
            this.http.post("https://api.mailgun.net/v3/" + this.mailgunUrl + "/messages", body, options)
                .map(result => result.json())
                .do(result => console.log("RESULT: ", JSON.stringify(result)))
                .subscribe(result => {
                    console.log("SENT!");
                    this.navCtrl.setRoot(TabsPage);
                    this.recipient = "";
                    this.subject = "";
                    this.message = "";
                }, error => {
                    console.log(error);
                });
        }
    }

}

这是控制台错误:

XMLHttpRequest cannot load https://api.mailgun.net/v3/<--My Domain-->/messages. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

1 个答案:

答案 0 :(得分:1)

CORS是 chrome 功能,可防止跨域请求,除非服务器允许。

在这种特殊情况下,服务器不接受授权标头。

如果你是从你的后端而不是镀铬那么这应该工作正常。

从你的后端做这个而不是有角度的。

此外,您不应将您的api密钥/秘密放在客户端上,因为它们已公开。