簡體   English   中英

Angular 2 如何發送郵件 PHP?

[英]Angular 2 How to send mail PHP?

我正在學習 angular 2,但我在網上沒有看到任何示例將一個簡單的聯系表從 angular 2 發送到 php 腳本。

我的html模板。

<form novalidate="" (ngSubmit)="guardar(forma)" #forma="ngForm">
    <div class="field">
        <label for="name">Nombre:</label>
        <input type="text"
               id="name"
               name="name"
               required
               minlength="3"
               ngModel>
    </div>

    <div class="field">
        <label for="email">Email:</label>
        <input type="email"
               id="email"
               name="email"
               required
               ngModel
               pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$">
    </div>

    <div class="field">
        <label for="message">Mensaje:</label>
        <textarea id="message"
                  name="message"
                  required
                  ngModel></textarea>
    </div>

    <div class="field">
        <button [disabled]="!forma.valid"
                type="submit">
            Enviar
        </button>
    </div>
</form>

PHP腳本

<?php
    $name = strip_tags(trim($_POST["name"]));
    $name = str_replace(array("\r","\n"),array(" "," "),$name);
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $message = trim($_POST["message"]);

    $recipient = "nexsmedia@gmail.com";
    $subject = "New contact from $name";

    $email_content = "Name: $name\n";
    $email_content .= "Email: $email\n\n";
    $email_content .= "Message:\n$message\n";

    $email_headers = "From: $name <$email>";

    mail($recipient, $subject, $email_content, $email_headers)
?>

我不完整的 angular 2 組件。 我已經在我的應用程序組件中導入了 HttpModule 和 FormsModule

import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Http } from '@angular/http';

@Component({
    selector: 'app-contacto',
    templateUrl: './contacto.component.html',
    styleUrls: ['./contacto.component.scss']
})
export class ContactoComponent {
    title = 'Contacto';

    constructor( private http: Http){}

    url='http://myUrl.com/mailerscript.php';

    name:string;
    email:string;
    message:string;

    guardar( forma:NgForm ) {

        this.name = 'name='+forma.value.name;
        this.email = 'email='+forma.value.email;
        this.message = 'message='+forma.value.message;

        /*??*/
        this.http.post(this.url, "");

    }
}

您似乎被困在 Angular 和 PHP 之間的接口上——這是可以理解的,因為它不像通過$_POST超全局變量訪問變量那么簡單。

默認情況下,Angular 將在請求正文中傳遞給它的數據作為json字符串提交,因此您必須訪問原始請求正文並將其解析為可用的 PHP 變量。

以下示例顯示了無需額外框架或其他依賴項即可執行此操作的最基本方法。 您可以(並且應該)遵循更好的組織實踐並將此內容移動到服務,但這會增加此處不需要的額外復雜層:

import { Component, OnInit } from '@angular/core';
import {Http} from "@angular/http";

@Component({
  selector: 'app-mailer',
  template: '<button (click)="sendEmail()">Send the Email</button>'
})
export class MailerComponent implements OnInit {

  email : string;
  name : string;
  message : string;
  endpoint : string;

  http : Http;

  constructor(http : Http) {
    this.http = http;
  }

  ngOnInit() {
    //This data could really come from some inputs on the interface - but let's keep it simple.
    this.email = "hpierce@example.com";
    this.name = "Hayden Pierce";
    this.message = "Hello, this is Hayden.";

    //Start php via the built in server: $ php -S localhost:8000
    this.endpoint = "http://localhost:8000/sendEmail.php";
  }

  sendEmail(){
    let postVars = {
      email : this.email,
      name : this.name,
      message : this.message
    };

    //You may also want to check the response. But again, let's keep it simple.
    this.http.post(this.endpoint, postVars)
        .subscribe(
            response => console.log(response),
            response => console.log(response)
        )
  }
}

和 PHP 腳本。 請注意,這會檢查多個請求方法。 它也檢查 OPTIONS 請求。 看看為什么這是必要的

為了盡可能簡單,我跳過了對來自 Angular的輸入的清理,這被認為是一個嚴重的安全問題。 您應該將其添加到面向生產的應用程序中:

<?php

switch($_SERVER['REQUEST_METHOD']){
    case("OPTIONS"): //Allow preflighting to take place.
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: POST");
        header("Access-Control-Allow-Headers: content-type");
        exit;
    case("POST"): //Send the email;
        header("Access-Control-Allow-Origin: *");

        $json = file_get_contents('php://input');

        $params = json_decode($json);

        $email = $params->email;
        $name = $params->name;
        $message = $params->message;

        $recipient = 'targetInbox@exmaple.com';
        $subject = 'new message';
        $headers = "From: $name <$email>";

        mail($recipient, $subject, $message, $headers);
        break;
    default: //Reject any non POST or OPTIONS requests.
        header("Allow: POST", true, 405);
        exit;
}

對於任何有興趣在更高版本的 Angular 中執行此操作的人,您會注意到@angular/http已被棄用並且不能在沒有錯誤的情況下使用。

您應該從 HPierce 執行上述所有操作,但您使用HttpClient代替:

import {HttpClient} from "@angular/common/http";

然后將所有類型轉換為HttpClient ,例如:

http : HttpClient;

  constructor( http: HttpClient) {
    this.http = http;
  }

而且您還需要將HttpClientModule導入您的app.module.ts

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM