Sending email with angular and php is very popular, so I adapted this code for Angular 4.


If you are working with Angular and you do not have a “real” backend, then you have maybe come across the problem that you can not send emails from your Angular website, but often you want to do it. Maybe ๐Ÿ™‚

Since this I found this question many times, more or less with Angular or Javascript, I thought to write this post explaining it using Angular.

I am assuming that you will have some basic knowledge in Angular.

So, since we are not able to send emails from Javascript or Angular, you will need the help of PHP. So lets create first our PHP Email “backend” like this:


So, let’s quickly see what we have here:

First, we are declaring the header to be of content type json. This we will need to send back the echo wich json_encode to our client in JSON format.


we are taking the url encoding and its values and storing it into a variable.

Then I have here some more variables with email addresses, contacts and message where i am creating the email body and subject.

Withย $headers .= “MIME-Version: 1.0\r\n”;ย $headers .= “Content-Type: text/html; charset=ISO-8859-1\r\n”; I am setting the content type as html, so I can use HTML when sending email, not just plain text. If you do not need that, remove it.

Then with the method mail(), we are sending the email to you and to the writer.

And finally sending a response.


So, that a user can fill in some data like name, email and the message, we will need to provide a HTML page where he can do that.


Here I am creating a form with inputs for name, email and the message.ย I am also binding the input to my message objectย in my component.


To handle our inputs from our html, we need our class which takes this responsibility. As said, that I assume that you are familiar with Angular, I will just say something relating to sending emails.



In this file is where the magic happens ๐Ÿ™‚

Here we are creating our service, where we are defining the path to our email.php as the url.

Then we create a method called sendEmail, which our component is calling.


That was it, with this, you are able to send emails with your Angular application without a “real” backend ๐Ÿ™‚



Working Link:ย





Send email with Angular4+ and PHP

Also published on Medium.

Tagged on:         

56 thoughts on “Send email with Angular4+ and PHP

  • Pingback: Angular2 Forms – Damir Kusar

  • April 14, 2016 at 3:19 pm

    Tanks man!! Fantastic post, helped me a lot.

    • July 5, 2016 at 8:53 am

      Hi Felipe,

      glad to hear that it helped.

  • May 20, 2016 at 2:30 pm

    Very nice job dude, thanks for this concise example.

    • July 5, 2016 at 8:53 am

      Hi Joss,

      You are very welcome ๐Ÿ™‚

  • July 3, 2016 at 5:39 pm

    Hi there, thanks for the guide.

    However, I get an error:

    No Directive annotation found on ContactService from the debugging tool. Do you know where it could comes from?

    Thanks in advance

    • July 5, 2016 at 8:56 am

      Hi Sebastien,

      no, not really. Hard to tell where it comes from. Very sorry.
      But check if everything is as it should, versions, typos and so on..

      • July 5, 2016 at 10:27 pm

        Hi Damir,

        Thank you for your comment, you were right about the syntax thing: I had set the providers as directives, that’s why it wasn’t working.

        I’m facing another issue now. It seems that Angular 2 is locking the email.php script. I have no idea why but it will send me an error message saying that the file can’t be found (error 404). However, if I copy past the its url in a new tab, my browser will download the email.php correctly.

        Do you know if Angular 2 is protected against php script?

        Thank you in advance!

        • July 12, 2016 at 8:31 am

          Hi Sebastien,

          actually, it should not be, it should work. Are you trying it locally? Since this might not work and when deploying on webserver, make sure php is activated / enabled on the server.

          • August 3, 2016 at 6:08 pm

            Hi Damir,

            I’m coming back to you really late, sorry about it.

            I didn’t find any solution to my issue, so finally, I decided to put the contact script on a remote machine and calling it directly. It’s working this way, so that makes me think that something in my angular 2 configuration is preventing accessing php files (and maybe other files too).

            I spent a lot of time trying to resolve it without success so I just gave up for now. If I find a solution in the future, I’ll make sure to come back here to share.

            Anyway, thanks for your tutorial, I’ve learnt a lot from it ๐Ÿ™‚

  • July 11, 2016 at 9:42 pm

    Hi Damir,

    It is very nice guide! I was using Angular RC 2 but I got a problem. The post response returned the code inside the php file and I kept getting “Unexpected token < in JSON at position 0". I just modified the import config and kept the other code the same as you. Do you have any idea what is going on? Thank you so much.

    • July 11, 2016 at 10:44 pm

      My fault. Uploaded to my host domain and everything worked. Thank you so much!

      • April 10, 2017 at 12:30 pm

        Hey, just wondering. I was having the same issue. Is it because I’m trying to work in local ?

  • November 4, 2016 at 5:01 pm

    I’m having an issue with this where when I attempt to send the email via the contact form either locally or on my live server, I get “Cannot POST /content/contactform/email.php”

    I get no other errors in the console, I have nothing except that it’s not found. I’ve googled and search stack overflow extensively and I can’t seem to find a reason why this doesn’t work. Do you have any suggestions?

    • January 31, 2017 at 3:41 pm

      Have you included it in your build process? is the file there where it should be?

  • January 4, 2017 at 7:23 pm

    Hello Damir,
    Thanks for this guide, it really helped. Although i am running into a single issue. I keep getting the following error when i send the email:
    “Error in retrieving news: SyntaxError: Unexpected number in JSON at position 4”
    Since i’m fairly new to this I have no idea why i keep getting this. The email sends as if everything works but i continue to get this error in the console. I commented out the following line and stopped getting the error, but not sure if i should:
    “.map(res => res.json())”
    Any idea why i am getting this error, or how to fix it

    • January 31, 2017 at 3:40 pm

      thank you for your message..

      this code is fairly old ๐Ÿ™‚ long time ago i wrote this ๐Ÿ™‚
      you can remove the map, since we are not really returning something from that post to map to.. so you do not need that map..

  • February 16, 2017 at 4:08 pm

    how do we put the angular files in the php server ? should we rename the index.html to index.php so it will be executed whenever we access the php apps ? Do you have any git to show about it ?

  • April 15, 2017 at 11:12 am

    Could you please provide the directory structure. I can’t get the response and the application shows the php file.

    • May 12, 2017 at 9:35 am

      Sadly i do not have the structure anymore.. post is already very old..

  • April 25, 2017 at 2:09 pm

    Thanks man .

    But i need your help .
    I am facing the issue with implementing this can you help me?

    getting following error please give me solution .

    core.es5.js:1084 ERROR Error: Uncaught (in promise): Error: No provider for ConnectionBackend!

      • May 12, 2017 at 9:32 am

        Is the file where it should be? is the file deployed there?

        • May 12, 2017 at 9:51 am

          ye i put file in assets but not work

    • May 12, 2017 at 9:34 am

      Not really something related to this topic, but if you have a new service, you have to import that service in your module in the provider section.

  • May 2, 2017 at 9:31 pm

    Hi Damir!!

    First, thanks for the useful guide. However, I was not able to send the email following your steps. I’ve tried using Angular 4.0.1 and @angular/cli: 1.0.0.

    When I build the application, the php file is not in the dist folder, so, how can the app find the php file path? Is this embedded in another file? Hiw this actually works?

    For example, in my app tree I have the php file in:


    What should I fill in private _contactUrl in contact.service?

    Thanks in advance!!

    • May 12, 2017 at 9:32 am

      I think you have to put that into the asset folder, so that angular cli takes that into the build..

  • May 18, 2017 at 5:59 pm

    Is there any way that you could update this for Angular4?

  • May 18, 2017 at 11:31 pm

    I’ve almost been able to put it all up in Angular 4. I separated the PHP file and put it in the assets folder. I have worked out all of the bugs and now get no errors. When I submit the form, I get the 200, which means that it should work. However, I never receive an email. Any idea why?

  • May 19, 2017 at 10:27 am

    Thanks Damir! Unfortunately… I still can’t seem to get it to work. I have downloaded the GitHub example and built it on a live server. I get no errors. In fact, it says that “Sending email was successful > e” and “AppComponent Success > e”. However, I still do not receive the email.

    Any idea what could be the problem here?


  • May 19, 2017 at 11:35 am

    There seems to be a lack of connection here. I changed the PHP file from



    mail(“”, “Contact message”);

    and it sent me an email.

    However, I couldn’t manage to get “$request->name”, “$request->email”, or “$request->message” to populate the email with any of that data.

    I also tried the POST method, “$_POST[‘name’]” for example, with no luck.

    Any idea what this could be?

    Thanks again Damir! ๐Ÿ™‚

  • May 19, 2017 at 5:29 pm

    Great update. Thanks a lot!

  • May 22, 2017 at 3:58 pm

    I was an idiot and forgot to redirect the email within cPanel… that was the problem! Doh! ๐Ÿ™‚

    Now it works! Thanks a lot Damir!

    • May 22, 2017 at 4:37 pm

      Hi Brad,

      very happy that you solved it.. ๐Ÿ™‚

    • December 20, 2017 at 9:17 pm

      What did you do to redirect email within cPanel? I am having the issue where everything works but no email comes through?

      • February 22, 2018 at 7:39 am

        Actually nothing.. dont know if your provider has to do something to enable that..

  • May 23, 2017 at 12:52 pm

    Hi Damir,

    I have following error on my local:
    npm start

    > angular-php-email-example@0.0.0 start /private/var/www/localhost/AngularPhpEmailExample
    > ng serve

    constructor(_configPath, schema, configJson, fallbacks = []) {

    SyntaxError: Unexpected token =
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:387:25)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object. (/private/var/www/localhost/AngularPhpEmailExample/node_modules/@angular/cli/models/config.js:3:18)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)

    npm ERR! Darwin 15.2.0
    npm ERR! argv “/usr/local/bin/node” “/usr/local/bin/npm” “start”
    npm ERR! node v5.10.1
    npm ERR! npm v4.0.5
    npm ERR! code ELIFECYCLE
    npm ERR! angular-php-email-example@0.0.0 start: ng serve
    npm ERR! Exit status 1
    npm ERR!
    npm ERR! Failed at the angular-php-email-example@0.0.0 start script ‘ng serve’.
    npm ERR! Make sure you have the latest version of node.js and npm installed.
    npm ERR! If you do, this is most likely a problem with the angular-php-email-example package,
    npm ERR! not with npm itself.
    npm ERR! Tell the author that this fails on your system:
    npm ERR! ng serve
    npm ERR! You can get information on how to open an issue for this project with:
    npm ERR! npm bugs angular-php-email-example
    npm ERR! Or if that isn’t available, you can get their info via:
    npm ERR! npm owner ls angular-php-email-example
    npm ERR! There is likely additional logging output above.

    npm ERR! Please include the following file with any support request:
    npm ERR! /private/var/www/localhost/AngularPhpEmailExample/npm-debug.log

    • May 23, 2017 at 2:58 pm

      Hi Naresh,

      You will need a newer node version.. you have 5.. install version 7.x

  • June 5, 2017 at 2:55 pm

    Hey Damir!

    Have you been able to send this with a hidden message? For some reason, mine won’t pick it up. Everything works if the type is text or from a dropdown selection, but when I try to pass something as you can see in the HTML, it doesn’t send it in the email.

    Any idea what could be the problem?

    For example, I have..


    TYPESCRIPT – contact.service.ts

    import { Injectable } from ‘@angular/core’;
    import { Http } from ‘@angular/http’;
    import { Observable } from ‘rxjs/Observable’;
    import { Resolve } from ‘@angular/router’;
    import ‘rxjs/add/operator/map’;
    import ‘rxjs/add/operator/catch’;

    export interface IMessage {
    name?: string,
    email?: string,
    room?: string,
    daterange?: string,
    message?: string

    export class AppService {
    private emailUrl = ‘/assets/email.php’;

    constructor(private http: Http) {


    sendEmail(message: IMessage): Observable | any {
    return, message)
    .map(response => {
    console.log(‘Sending email was successfull’, response);
    return response;
    .catch(error => {
    console.log(‘Sending email got error’, error);
    return Observable.throw(error)

    and PHP

    $from_name = $request->name;

    $to_email = “”;

    $contact = “Name: $from_name
    Email: $request->email
    Room: $request->room
    Dates: $request->daterange”;
    $content = “Message:$message”;

    $website = ‘My Wicked Awesome Website’;
    $email_subject = “$website: Received a message from $from_name”;

    $email_body = ”;
    $email_body .= “$contact $content”;
    $email_body .= ”;

    $headers .= “MIME-Version: 1.0\r\n”;
    $headers .= “Content-Type: text/html; charset=ISO-8859-1\r\n”;
    $headers .= “From: $from_email\n”;
    $headers .= “Reply-To: $from_email”;

    $result = mail($to_email,$email_subject,$email_body,$headers);

    $response_array[‘status’] = ‘success’;
    $response_array[‘from’] = $from_email;
    $response_array[‘result’] = $result;

    echo json_encode($response_array);

    return $from_email;
    } else {
    $response_array[‘status’] = ‘error’;
    echo json_encode($response_array);
    header(‘Location: /error.html’);

    Thanks!! ๐Ÿ™‚

    • June 5, 2017 at 2:57 pm

      For some reason, it cut out the HTML, let me re-post that. I’ll remove the

      form (submit)=”sendEmail(message)” #f=”ngForm”
      input type=”text” value=”TheEnsuite” id=”room” name=”room” [(ngModel)]=”” #room=”ngModel” /
      button type=”submit” class=”btn btn-success” [disabled]=”f.invalid” *ngIf=”!f.submitted”

    • June 19, 2017 at 2:53 pm

      Hi Brad,

      sorry for late response.. a lot going on ๐Ÿ™‚

      you haven’t specified the variable $message in your PHP in $content = โ€œMessage:$messageโ€, you just have message; Could that cause the problem?

    • June 19, 2017 at 3:10 pm

      Hi, I have some trouble with
      $postdata = file_get_contents(“php://input”);
      $request = json_decode($postdata);

      It seem that $request have no data, because a get an empty message

      And if i change this
      $message = $request->message;
      $message = ‘SOME TEXT’

      IT is give me my message

      Have you some idea?

  • August 14, 2017 at 4:03 pm

    Thank you, thank you and thank you ! You saved my time! Cheers! from your brazilian friend!

  • September 4, 2017 at 9:05 am

    Hi Damir,

    Firstly, thank you for a great tutorial, it is very well put together ๐Ÿ™‚

    I’ve been trying to get it working locally and want to make sure it’s working 100% before releasing to production, however am receiving a “http://localhost:4200/assets/email.php 404 (Not Found)” error in the console.

    From reading the comments above, it would appear that there is no way of getting it to work locally, however, I am not ready to deploy my site to production as yet to test. Is there any work around I can use? Please detail the steps.

    Thanks again, I appreciate your help!


    • February 22, 2018 at 7:49 am

      Hi Steven,

      you cant really test that locally.. you are not able to execute this php and send emails, maybe there are solutions for that.. but never looked it for that.

  • October 30, 2017 at 3:11 pm

    Nice posting. Is this still work? There is an update tools?

    • February 22, 2018 at 7:42 am

      Haven’t tested it for longer time, i think it should still work.. but you have to deploy it to a server.

  • January 25, 2018 at 9:08 am

    If we are waiting with angular and php we sometimes need the email to be send so use the tips and tutorial and get your email send.


Leave a Reply


Get every new post on this blog delivered to your Inbox.

Join other followers:

Welcome Damir Kusar

Log in

Lost your password?
%d bloggers like this: