1

After many search, my problem is still here. I'm new with angular and i try to send a mail in my personnal adresse after validate a contact form.

I have no mail after submit but if i copy and past the file mail.php in my server and i ping in i have a mail with default values.

When i use postman aplication a have the return of echo in my mail.php

I need your help

Here my contact.component.ts

  import { Component, OnInit } from '@angular/core';
import { FormGroup , FormControl, Validators } from '@angular/forms';
import { Http }    from '@angular/http';

@Component({
  selector: 'contact',
  templateUrl: './contact.component.html',
  styles:['input.ng-invalid {border-left: 5px solid red;}',
    'input.ng-valid {border-left:5px solid green;}',
    'input.ng-pristine {border-left: 1px solid grey;}',
    'textarea.ng-invalid {border-left: 5px solid red;}',
      'textarea.ng-valid {border-left:5px solid green;}',
      'textarea.ng-pristine {border-left: 1px solid grey;}']
  // styleUrls: ['../../app.component.css']
})
export class ContactComponent implements OnInit {

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

    http : Http;

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

    userForm = new FormGroup({
        nom: new FormControl(null),
        prenom: new FormControl(null),
        email: new FormControl(null),
        telephone: new FormControl(null),
        message: new FormControl(null)
    });

    onSubmit(){
        console.log(this.userForm.value);
        let postVars = {
          email : this.email,
          name : this.name,
          message : this.message
        };
            this.endpoint = "http://localhost:8000/src/app/page/contact/mail.php";
        this.http.post(this.endpoint, postVars)
        .subscribe(
            response => console.log(response),
            response => console.log(response)
        )
    }

    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/src/app/page/contact/mail.php";
    }


}

here my contact.component.html

<main>
    <div class="container">
        <div class="row">
            <p class="col-xs-12 text-center">Vous desirez discuter un moment?</p>
            <p class="col-xs-12 text-center">Vous etes sur au bon endroit ?</p>
        </div>
        <form [formGroup]="userForm" method="POST" (ngSubmit)="onSubmit()">
            <div class="form-group">
                <label>Nom</label>
                <input type="text" name="nom" #refNom class="form-control" formControlName="nom">
                <b>{{refNom.className}}</b>
                <div class="alert alert-danger" *ngIf="userForm.controls['nom'].hasError('required') && ( userForm.controls['nom'].touched)">
                    Merci de rentrer un nom
                </div>
                <div class="alert alert-danger" *ngIf="userForm.controls['nom'].hasError('minlength')">
                    Il faut écrire un nom avec plus de deux characteres
                </div>
                <div class="alert alert-danger" *ngIf="userForm.controls['nom'].hasError('maxlength')">
                    Vous n'avez pas un diminutif?
                </div>
            </div>
            <div class="form-group">
                <label>Prenom</label>
                <input type="text" #refPrenom class="form-control" formControlName="prenom">
                <b>{{refPrenom.className}}</b>
                <div class="alert alert-danger" *ngIf="userForm.controls['prenom'].hasError('required') && ( userForm.controls['prenom'].touched)">
                    Merci de rentrer un prénom
                </div>
                <div class="alert alert-danger" *ngIf="userForm.controls['prenom'].hasError('minlength')">
                    Il faut écrire un prénom avec plus de deux characteres
                </div>
                <div class="alert alert-danger" *ngIf="userForm.controls['prenom'].hasError('maxlength')">
                    Vous n'avez pas un diminutif?
                </div>
            </div>
            <div class="form-group">
                <label>email</label>
                <input type="email" name="email" class="form-control" formControlName="email">
            </div>
            <div class="form-group">
                <label for="telephone">Telephone</label>
                <input type="text" class="form-control" formControlName="telephone">
            </div>
            <div class="form-group">
                <label for="message">Votre message</label>
                <textarea class="form-control" name="message" id="exampleTextarea" rows="3" formControlName="message"></textarea>
            </div>
            <button type="submit" [disabled]="!userForm.valid" class="btn btn-primary">Submit</button>
        </form>
    </div>
</main>

here my mail.php file

    <?php
$recipient = '[email protected]\n';
$subject = 'new message\n';
$headers = "From: \n";
$message = '$params->message\n';
mail('[email protected]', 'mon sujet', 'coucou');

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\n';

        $recipient = '[email protected]\n';
        $subject = 'new message\n';
        $headers = "From: [email protected]\n";
        if(mail($recipient, $subject, $message, $headers)){
            echo'totooo';
        }
    //    mail($recipient, $subject, $message, $headers);
        break;
    default: //Reject any non POST or OPTIONS requests.
        header("Allow: POST", true, 405);
        exit;
}
?>

i have no error on the bash for ng serve and on the bash php -S localhost:8000 i can see [Thu Apr 13 14:41:37 2017] 127.0.0.1:34118 [200]: /src/app/page/contact/mail.php

i dont know how to fix this.

3
  • Possible duplicate of Sending an email with AngularJS and PHP? Commented Apr 13, 2017 at 13:26
  • The problem is i have no email with simple quote value. i think angular dont go in my mail.php file when submit form and i dont know why Commented Apr 13, 2017 at 13:31
  • Or where i can put this code in mine ?? Commented Apr 13, 2017 at 13:58

1 Answer 1

2

Try and set the url parameter with URLSearchParams and use RequestOptions and set headers with x-www-form-urlencoded. I also noticed the weird use of Http, remove declaring http in component: http : Http;

and change your constructor to:

constructor(private http : Http) { }

But back to the POST request. Import the following:

import { RequestOptions, URLSearchParams, Headers } from '@angular/http';

Your onSubmit:

onSubmit(){
  let body = new URLSearchParams();
  body.set('email', this.email);
  body.set('name', this.name);
  body.set('message', this.message);

  let headers = new Headers();
  headers.append('Content-Type', 'application/x-www-form-urlencoded');
  let options = new RequestOptions({ headers: headers });

  this.endpoint = "http://localhost:8000/src/app/page/contact/mail.php";

    this.http.post(this.endpoint, body, options)
      .subscribe(
        response => console.log(response)
    )
}

Hopefully this helps! Furthermore, I suggest you move all your http request to an actual service, that is usually the way to do it ;)

Sign up to request clarification or add additional context in comments.

5 Comments

I have an error " cannot post/contact" in the page after submit my form. Thank for your interest in my problem.
Did you make the changes with removing http:Http and just having the http injected in the constructor?
Thank a lot it's work without error :) you say i need to move all my http request to an actual service. What do you want say by that ? I'm new with dev ^^
You are welcome! Well you do not have to make a service, but this is usually how we do it. Handle all http requests in a service, and then just subscribe in the component. As per can be seen in the official docs, they are also using a separate service for http-requests: angular.io/docs/ts/latest/guide/server-communication.html
Thank for advice. Now i need make in another page a database call and display the content. I will refactoring my code before ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.