Angular 2 How to send mail PHP?

前端 未结 2 1936
庸人自扰
庸人自扰 2020-12-30 18:21

I learning angular 2, and I don\'t see any example on the web to send a simple contact form from angular 2 to php scrip.

My html template.



        
相关标签:
2条回答
  • 2020-12-30 18:43

    For anyone that's interested in doing this in later versions of Angular, you'll notice that @angular/http is deprecated and cannot be used without an error.

    You should do all the above from HPierce but you use HttpClient instead:

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

    Then convert all your types to HttpClient instead, e.g.:

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

    And you'll also need to import HttpClientModule into your app.module.ts!

    0 讨论(0)
  • 2020-12-30 18:55

    You seem to be stuck on the interface between Angular and PHP - it's understandable because it's not as trivial as accessing variables via the $_POST superglobal.

    By default, Angular submits data passed to it in the request body as a json string, so you have to access the raw request body and parse it into usable PHP variables.

    The following example shows the most basic way to do this without extra frameworks or other dependencies. You could (and should) follow better organization practices and move this content to a service, but that's adding an extra layer of complication that isn't needed here:

    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)
            )
      }
    }
    

    And the PHP script. Note that this checks for multiple request methods. It checks for an OPTIONS request too. See why this is nessesary.

    In order to keep this as simple as possible, I've skipped sanitizing the input from Angular, which is considered a severe security issue. You should add that in for production facing apps:

    <?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;
    }
    
    0 讨论(0)
提交回复
热议问题