Angular 2 – Sending mails from your app.

Hi Friends,

Hope you are all well. This post deals with sending mails from your angular 2 application using emailjs. It’s simple and pretty much easier to implement. Please note that you will need a email server in order to implement this.

I will be using the email server that came along with this domain (tphangout.com).

Let’s begin.

A screencast of this tutorial

The complete code in this tutorial is available below

Angular 2 app – click here

Backend (Nodejs) – click here

First, let’s scaffold out a new application using the below command. (You need to have the angular-cli tool for this).

Now rather than creating a simple page with a few fields and sending out an email, we will use a real-time use case. Assume that we have an app for which a user can signup using his email id and password. Once he has signed up successfully then the system will send out an email welcoming him. This is what we are trying to build now.

So let’s open up the app.component.html and add the below code to make it look like a signup form.

As you can see, I have used styling. So let’s include the bootstrap-material links to the index.html. (Feel free to use any styling framework of your choice).

This is what index.html looks like now.

Also in the app.component.css file add the below code for keeping the form in the middle.

Now, that we have got the eye-candy stuff out of the way, open up app.component.ts and add the below code.

I have a simple object newUser which contains two properties namely username & password. I also have a method called addUser() which will call a method called addNew present in the user service. Let’s go ahead and create that service.

To create a service give the below command.

Now open the users.service.ts and add the below code.

Let’s break this down.

  1. In the service we just have one method called addNew which takes in the usercreds as an argument and then makes a http call to the rest endpoint /adduser.
  2. If the call is successful, i.e., if the user is added to the database then another http call is made to the rest endpoint /sendmail.
  3. Note that we are sending the username alone to the second call, and if the call is successful, i.e., if the mail is sent we are simply logging a message on the console.

Okay. Let’s wire up the backend then.

For the backend, we can use our trusted authentication backend. As you might have noticed, I have already added a adduser method to it long back. Grab a copy of the repo from here.

Or simply clone the repo using the below command.

Now let’s install emailjs. Use the below command.

Once this is done open up methods -> actions.js and add a reference to emailjs at the top.

Now add a new method below the getinfo method as shown below.

Let’s break this down.

  1. If you notice, while connecting I pass in a lot of parameters. These are for the server config.
  2. After connecting, we pass in the recipient’s email using the email id which we received through req params. (req.body.name).
  3. We are also attaching a zip file along with the mail and we have a call back function which returns true if the mail is sent successfully.

Now open up routes -> routes.js file and add a route for this function as shown below.

Okay, now that everything is in place. Let’s fire up our database and get it running. Once it is ready then start the backend using the below command.

And start the front-end using the below command.

Just give up your email id and try signing up, if everything goes fine then you would see a mail in your inbox with our attached zip file.

Hope this helped you guys.

Thanks for reading. Peace.. :)

 

Liked it? Take a second to support admin on Patreon!
  • Shamroz Warraich

    bravooo man… you rock.. :::P

  • arsene

    possible to use it with ionic 2?

    • yes bro.. you just need to make a http call from your app to the REST Api endpoint..

  • Amar

    Hey, Thanks a lot for tutorial. Great Job mate. I am facing small issue. I am getting this error:

    res.json({success: true, msg: ‘sent’});

    ^

    TypeError: res.json is not a function

    • Try using return res.json({success: true, msg: ‘sent’})

      • Amar

        Still same error 😐

      • Elson Jim Abao-an Pialago

        can you make a typescript code im using angular 2 ty

  • jussjosh

    Hi, I tried installing ionic-authentication and got an error trying to run it:

    ionic-authentication/node_modules/bindings/bindings.js:83
    throw e
    ^

    Error: dlopen(/ionic-authentication/node_modules/bcrypt/build/Release/bcrypt_lib.node, 1): no suitable image
    found.

    • dav

      just run the command line : npm install bcrypt

  • Nishant Sharma

    Hi Raja,
    I have an issue of generating sitemap for an angular website. I am using simphony as a backend and systemjs as a loader for app.

  • Ricky

    Hi Raja, thanks a lot this tutorial. I have a question where to find action.js in a Angular 2 CLI? I am very new in Angular.

  • dav

    Hi, i have this error in my console browser : Error: Response with status: 404 Not Found for URL: http://localhost:3333/sendmail

    My node server is running in port 3333.
    I have implemented the sendEmail function side node

    I would like just send an email. Side Angular :

    this.http.post(‘http://localhost:3333/sendmail’, emailid, {headers: headers}).subscribe((data) => {

    if (data.json().success) {

    console.log(‘Sent successfully’);

    }

    });

    Can you help me please?

    • Elson Jim Abao-an Pialago

      getContact(contactNum: string, storeName: string, cityName: string, emailAdd: string, clientMessage: string): void {
      this._emailService.sendMail(contactNum, storeName, cityName, emailAdd, clientMessage).subscribe(
      (contact: any) => this.mail = contact
      );

  • Elson Jim Abao-an Pialago

    how to do in typescript code?
    via gmail or yahoo..
    Any help..ty