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"

    <div class="field">
        <label for="email">Email:</label>
        <input type="email"

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

    <div class="field">
        <button [disabled]="!forma.valid"

PHP script

    $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 = "";
    $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';

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

    constructor( private http: Http){}



    guardar( forma:NgForm ) { = 'name='; = 'email=';
        this.message = 'message='+forma.value.message;

        /*??*/, "");


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

  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. = ""; = "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";

    let postVars = {
      email :,
      name :,
      message : this.message

    //You may also want to check the response. But again, let's keep it simple., postVars)
            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:


    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");
    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 = '';
        $subject = 'new message';
        $headers = "From: $name <$email>";

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

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 *