2017-02-28 60 views
0

我学习角2,我没有看到任何Web上的例子发送一个简单的联系表单从角2到PHP scrip。Angular 2如何发送邮件PHP?

我的模板。

<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._%+-][email protected][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 = "[email protected]"; 
    $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) 
?> 

我的不完整的角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, ""); 

    } 
} 

回答

1

你似乎被卡住之间的界面上角和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 = "[email protected]"; 
    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请求。 See why this is nessesary

为了尽可能简单,我已经跳过了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 = '[email protected]'; 
     $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; 
}