The Techies' pub

Angular 2 – Sending mails from your app.

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

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

1

ng newangularemail

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.

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

1

2

3

4

5

6

7

.center-div

{

top:50%;

left:50%;

transform:translate3d(-50%,-50%,0);

position:absolute;

}

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

import{Component}from'@angular/core';

import{UsersService}from'./users.service';

@Component({

moduleId:module.id,

selector:'app-root',

templateUrl:'app.component.html',

styleUrls:['app.component.css']

})

exportclassAppComponent{

newUser={

username:'',

password:''

}

constructor(privateuserservice:UsersService){}

addUser(){

this.userservice.addNew(this.newUser);

}

}

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.