Angular 2 How to send mail PHP?

Posted on

Angular 2 How to send mail PHP? – Here in this article, we will share some of the most common and frequently asked about PHP problem in programming with detailed answers and code samples. There’s nothing quite so frustrating as being faced with PHP errors and being unable to figure out what is preventing your website from functioning as it should like php and angular . If you have an existing PHP-based website or application that is experiencing performance issues, let’s get thinking about Angular 2 How to send mail PHP?.

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.

<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 script

<?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: $namen";
    $email_content .= "Email: $emailnn";
    $email_content .= "Message:n$messagen";

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

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

My incomplete angular 2 component.
I already have imported in my app component HttpModule and 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, "");

    }
}

Solution :

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

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!

Leave a Reply

Your email address will not be published. Required fields are marked *