Sending Emails with Angular App

Forbes, BMW Driveaway Price Calculator, and many other apps are built with Angular. If you’re reading this, you’ve probably also opted for this front-end framework or, at least, are considering it.  And sooner or later, you’ll need to send transactional emails from your app. This is what we’re going to deal with today.

Backend is required to send emails with Angular

You can’t send a message directly with Angular. It is a front-end framework, i.e. it works at the client-side. Email sending functionality is server-side stuff. So, you most likely have a backend that gets requests from your Angular app to send messages. We’ve already blogged about the most common options for this, so check out the following tutorials:

If you haven’t decided on the backend yet, Node.js can be a great pick. Let’s say you want to implement a contact form or another type of functionality that will send an email from your Angular app. In this case, you need to use a Node.js server that will send your emails. Here are some options you can choose from.

Sending an HTML email with Nodemailer 

Step 1: The package.json file is what we begin with. Here is the code it will contain:

{
  "name": "sendemail",
  "version": "1.0.0",
  "description": "sending emails from Angular through Node.js"
  "main": "server.js"
  "dependencies": {
    "nodemailer": "<latest-version>",
    "express": "<latest-version>",
    "body-parser": "<latest-version>",
    "cors": "<latest-version>"
  }
}

Step 2: Install the dependencies and modules to implement your email client:

  • Express.js to create a server
  • Nodemailer to send email from node.js
  • Body-parser to parse the data that comes from Angular and convert it to an object

For this, execute the following:

npm install express body-parser cors nodemailer

Step 3: Create a server file. Let’s call it Server.js. It should contain the following code:

//import modules installed at the previous step. We need them to run Node.js server and send emails
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const nodemailer = require("nodemailer");

// create a new Express application instance 
const app = express();

//configure the Express middleware to accept CORS requests and parse request body into JSON
app.use(ra origin: "*" }));
app.use(bodyParser.json());

//start application server on port 3000
app.listen(3000, () => {
  console.log("The server started on port 3000");
});

// define a sendmail endpoint, which will send emails and response with the corresponding status
app.post("/sendmail", (req, res) => {
  console.log("request came");
  let user = req.body;
  sendMail(user, (err, info) => {
    if (err) {
      console.log(err);
      res.status(400);
      res.send({ error: "Failed to send email" });
    } else {
      console.log("Email has been sent");
      res.send(info);
    }
  });
});

Step 4: Add the following lines of code to set configuration of Nodemailer:

const sendMail = (user, callback) => {
  const transporter = nodemailer.createTransport({
    host: "smtp.gmail.com",
    port: 587,
    secure: false,
    auth: {
      user: "<sender email>",
      pass: "<password>"
    }
  }); 
}

Step 5: Define the options of your email like to/from-headers, subject line, and body text:

const mailOptions = {
  from: `"<Sender’s name>", "<Sender’s email>"`,
  to: `<${user.email}>`,
  subject: "<Message subject>",
  html: "<h1>And here is the place for HTML</h1>"
};

transporter.sendMail(mailOptions, callback);

Run your backend by executing node server.js. After running the server, you still need to test your endpoint. For example, you can run curl -X POST http://localhost:3000/sendmail in the console.  
Read more about how to send emails with Nodemailer in our dedicated blog post. And now, let’s check out another Node.js solution for your Angular app.

Sending an email with attachments using emailJS 

If Nodemailer allows you to choose from different email sending methods like SMTP, AWS SES, and sendmail, emailJS is a pure SMTP-oriented package. Here is the flow you should use:

Step 1: Install emailJS

npm install emailjs --save

Step 2: Add a new method. 

Open your methods file and add a reference to emailjs using the require() function. 

var email  = require('emailjs/email');

Add a new method for email sending and configure the SMTP server:

sendmail: function(req, res) {
        
var server  = email.server.connect({
   user:    "<sender’s-email>", 
   password:"<sender’s-password>", 
   host:    "smtp.your-email.com", 
   ssl:     true
   port: 465
});

Step 3: Define the mail options:

server.send({
   text:    "Your message body text", 
   from:    "<sender’s email>", 
   to:      <recipient’s email>,
   subject: "Your message subject",
   attachment: 
   [
      {data:"<html><strong>A bit of HTML text</strong></html>", alternative:true},
      {path:"user/desktop/file.pdf", type:"application/pdf", name:"renamed.pdf"}
   ]
}, function(err, message) { 
    if(err)
    console.log(err);
    else
    res.json({success: true, msg: 'sent'});
 });     
    }

Step 4: Add a route for this function in the routes.js file

router.post('/sendmail', actions.sendmail);

Run your backend by executing node server.js

Linking your Angular app to the server

Once you have your Node.js server implemented, you need to couple it with your Angular code. For this, we’ll create a service in the client part that will make requests to the server.

ng generate service Message

It will create a Message.service.ts file, in which you need to code as follows:

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/http';
 
@Injectable()
export class MessageService {
 
  constructor(private_http: HttpClient) {}
 
  sendMessage(body) {
    return this._http.post(‘http://localhost:3000/sendmail', body);
  }
}

HttpClient will make requests to your backend. sendMessage() receives an object (data sent from the app) as a parameter. The service is ready and we need to make several imports in the main module. Here’s how the file will look:

import { BrowserModule } from ‘@angular/platform-browser’;
import { NgModule } from ‘@angular/core’;
import { HttpClientModule } from ‘@angular/common/http’;
import { FormsModule } from ‘@angular/forms’
import { AppComponent } from ‘./app.component’;
import { MessageService } from ‘./services/message.service’;
@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, HttpClientModule, FormsModule],
  providers: [MessageService],
  bootstrap: [AppComponent]
})
export class AppModule { }

That’s it. So, to sum up. In Node.js (backend), we installed the necessary packages to create the email service and configured Nodemailer. Also, we created a server that will send transactional emails based on the data received from your Angular app. Feel free to read more about sending emails with Node.js in our dedicated blog post.

In Angular (frontend), we created a service to make a POST request to the backends’ endpoint. Also, we imported modules to work with http and form requests, as well as our service to link Angular with Node.js.

How to make sure that transactional emails from my Angular app reach the inbox?

You don’t have to reinvent the wheel to test the email sending capability of your app. Certainly, you can send a message to a real user and see if he or she has it in their inbox. But this method has drawbacks, and does not guarantee success. Mailtrap is always at hand, and it allows you to check both whether the message hit its target and what it looks in the inbox. Here’s what you should do:

  • Step 1: Launch your coffee maker 
  • Step 2: Sign up to Mailtrap and 
  • Step 3: Open your Demo inbox and press Settings (gear-wheel)
  • Step 4: Select Node.js> Nodemailer in the Integrations drop-down menu and replace the configuration of your Nodemailer with the provided code. Also, you can tweak your code manually using the provided SMTP credentials like host, port, etc.:
var transport = nodemailer.createTransport({
  host: "smtp.mailtrap.io",
  port: 2525,
  auth: {
    user: "94b784b5970edf",
    pass: "01a5d515011f6e"
  }
});
  • Step 5: Send the email and check your Demo inbox. 
  • Step 6: Your coffee is ready:)

In conclusion, we’d like to repeat that Angular can’t send emails by itself. Always make sure to create a server for this. Alternatively, you can opt for an email API. Read more on this in Send Emails via Gmail API. Good luck in your dev endeavors!