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:

email.php

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.

With

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.

html

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.

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.

 

service

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: http://angularphpemailexample.kusar.ch/

Github: https://github.com/damirkusar/AngularPhpEmailExample

 

 

 

Send email with Angular4+ and PHP

Also published on Medium.

Tagged on:         

45 thoughts on “Send email with Angular4+ and PHP

  • Pingback: Angular2 Forms – Damir Kusar

  • April 14, 2016 at 3:19 pm
    Permalink

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

    Reply
    • July 5, 2016 at 8:53 am
      Permalink

      Hi Felipe,

      glad to hear that it helped.

      Reply
  • May 20, 2016 at 2:30 pm
    Permalink

    Very nice job dude, thanks for this concise example.

    Reply
  • July 3, 2016 at 5:39 pm
    Permalink

    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

    Reply
    • July 5, 2016 at 8:56 am
      Permalink

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

      Reply
      • July 5, 2016 at 10:27 pm
        Permalink

        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!

        Reply
        • July 12, 2016 at 8:31 am
          Permalink

          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.

          Reply
          • August 3, 2016 at 6:08 pm
            Permalink

            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
    Permalink

    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.

    Reply
    • July 11, 2016 at 10:44 pm
      Permalink

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

      Reply
      • April 10, 2017 at 12:30 pm
        Permalink

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

        Reply
  • November 4, 2016 at 5:01 pm
    Permalink

    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?

    Reply
    • January 31, 2017 at 3:41 pm
      Permalink

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

      Reply
  • January 4, 2017 at 7:23 pm
    Permalink

    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

    Reply
    • January 31, 2017 at 3:40 pm
      Permalink

      Hi,
      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..

      Reply
  • February 16, 2017 at 4:08 pm
    Permalink

    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 ?

    Reply
  • April 15, 2017 at 11:12 am
    Permalink

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

    Reply
    • May 12, 2017 at 9:35 am
      Permalink

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

      Reply
  • April 25, 2017 at 2:09 pm
    Permalink

    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 .

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

    Reply
      • May 12, 2017 at 9:32 am
        Permalink

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

        Reply
        • May 12, 2017 at 9:51 am
          Permalink

          ye i put file in assets but not work

          Reply
    • May 12, 2017 at 9:34 am
      Permalink

      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.

      Reply
  • May 2, 2017 at 9:31 pm
    Permalink

    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:

    src/app/components/contact/mail.php

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

    Thanks in advance!!

    Reply
    • May 12, 2017 at 9:32 am
      Permalink

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

      Reply
  • May 18, 2017 at 5:59 pm
    Permalink

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

    Reply
  • May 18, 2017 at 11:31 pm
    Permalink

    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?

    Reply
  • May 19, 2017 at 10:27 am
    Permalink

    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?

    Thanks

    Reply
  • May 19, 2017 at 11:35 am
    Permalink

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

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

    to

    mail(“mypersonalemail@gmail.com”, “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! 🙂

    Reply
  • May 19, 2017 at 5:29 pm
    Permalink

    Great update. Thanks a lot!

    Reply
  • May 22, 2017 at 3:58 pm
    Permalink

    I was an idiot and forgot to redirect the email within cPanel… that was the problem! Doh! 🙂

    Now it works! Thanks a lot Damir!

    Reply
    • May 22, 2017 at 4:37 pm
      Permalink

      Hi Brad,

      very happy that you solved it.. 🙂

      Reply
  • May 23, 2017 at 12:52 pm
    Permalink

    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

    /private/var/www/localhost/AngularPhpEmailExample/node_modules/@angular/cli/models/config/config.js:16
    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

    Reply
    • May 23, 2017 at 2:58 pm
      Permalink

      Hi Naresh,

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

      Reply
  • June 5, 2017 at 2:55 pm
    Permalink

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

    HTML

    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
    }

    @Injectable()
    export class AppService {
    private emailUrl = ‘/assets/email.php’;

    constructor(private http: Http) {

    }

    sendEmail(message: IMessage): Observable | any {
    return this.http.post(this.emailUrl, 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

    message;
    $from_name = $request->name;

    $to_email = “myemailaddress@gmail.com”;

    $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);

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

    Thanks!! 🙂

    Reply
    • June 5, 2017 at 2:57 pm
      Permalink

      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)]=”message.room” #room=”ngModel” /
      button type=”submit” class=”btn btn-success” [disabled]=”f.invalid” *ngIf=”!f.submitted”

      Reply
    • June 19, 2017 at 2:53 pm
      Permalink

      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?

      Reply

Leave a Reply

Follow

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: