Site icon Mailtrap

Sending Emails with Angular App

Angular, as a front-end framework, does not have the capability to directly send emails. It runs in the browser and does not have access to the server’s email sending functionality due to security reasons.


To implement email functionality with an Angular application, Angular has to send a request to a server-side API. And you need to set it up using Node.js, Python, Java, etc. Then the server-side application handles the task of sending an email using an SMTP server or an email delivery platform like Mailtrap.

The described flow is covered in detail in this article including ready made code examples and explanations.

Using Node.js as a backend for Angular apps

Let’s say you want to implement a contact form or another type of functionality that will send emails from your Angular app. In this case, you need to use a Node.js server that will send your emails. The tutorials throughout this article use Node.js.

If you’re looking for frameworks other than Node.js, we’ve already blogged about the most common options. So check the following tutorials:

Sending an HTML email with Nodemailer 

Step 1: The package.json file is what we begin with. Note that it contains “multer” to handle file attachments, and “dotenv” to store credentials.

Here’s the code:

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

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

For this, execute the following:

npm install express body-parser cors nodemailer multer dotenv

Step 3: Create an .env file and populate it with required credentials:

PORT=3001
MAILTRAP_USER=
MAILTRAP_PASS=
SMTP_HOST=live.smtp.mailtrap.io
SMTP_PORT=2525
SENDER_EMAIL=
RECIPIENT_EMAIL=
CORS_ORIGIN=

Step 4: Create email-template.html with placeholders for the email template:

<!doctype html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>

<body style="font-family: sans-serif;">
    <h1 style="font-size: 18px; font-weight: bold; margin-top: 20px">New message</h1>
    <p>Subject: {{subject}} <br> From: {{name}} <br> Email: {{email}}</p>
    <p>Message:</p>
    <p>{{message}}</p>
</body>

</html>

Step 5: Start creating a server file, by importing the necessary modules. And let’s call it Server.js:

const dotenv = require('dotenv');
const express = require('express');
const bodyparser = require('body-parser');
const nodemailer = require('nodemailer');
const fs = require('fs');
const cors = require('cors');
const multer = require('multer');

Step 6: Configure dotenv, initialize Express, and configure middleware:

dotenv.config();

//create a new Express instance
const app = express();
//store the port
const port = process.env.PORT || 3000;

//configure the Express middleware to accept Angular miltipart/form-data needed for the attachment and parse request body into .json
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());

//define the cors options
const corsOptions = {
    origin: process.env.CORS_ORIGIN,
    optionSuccessStatus: 200
};

//configure the Express middleware to use the cors option we defined
app.use(cors(corsOptions));

Step 7: Set up email template handling:

//store email template path and store the emailTemplate in templateContent
const templatePath = 'email-template.html';
const templateContent = fs.readFileSync(templatePath, 'utf-8');

// create a function to replace placeholders in the email template with received data
function replacePlaceholders(html, data) {
    for (const key in data) {
        if (data.hasOwnProperty(key)) {
            const placeholder = `{{${key}}}`;
            html = html.replace(new RegExp(placeholder, 'g'), data[key]);
        }
    }
    return html;
}

Step 8: Configure multer, define email sending endpoint, and start the server:

// configure multer to use memory storage to receive attachment
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });

// define send endpoint, which will send emails and response with the corresponding status
app.post('/send', upload.single('file'), async (req, res) => {
    try {
        const { name, subject, email, message } = req.body;

        // extra backend validation
        if (!name || !subject || !email || !message) {
            return res.status(400).json({ error: 'Missing required fields' });
        }

        // store attachment if provided
        const attachmentData = req.file ? {
            filename: req.file.originalname,
            content: req.file.buffer
        } : null;

        // create nodemailer transport
        const transporter = nodemailer.createTransport({
            host: process.env.SMTP_HOST,
            port: process.env.SMTP_PORT,
            auth: {
                user: process.env.MAILTRAP_USER,
                pass: process.env.MAILTRAP_PASS
            }
        });

        // replace placeholders in the email template with received data
        const emailHtml = replacePlaceholders(templateContent, { name, subject, email, message });

        // define the options of your email like to/from-headers, subject line, body text, html and attachment
        const mailOptions = {
            from: process.env.SENDER_EMAIL,
            to: [process.env.RECIPIENT_EMAIL, 'secondRecipient@example.com'],
            subject: `New message from ${name} with subject ${subject}`,
            text: `New message \n\nSubject: ${subject}\nFrom: ${name}\nEmail: ${email}\n\nMessage:\n\n${message}`,
            html: emailHtml,
            attachments: attachmentData ? [attachmentData] : []
        };

        // store send mail response
        const info = await transporter.sendMail(mailOptions);

        // provide console feedback and return a positive response to the client
        console.log('Email sent:', info.response);
        res.status(200).json({ message: 'Email sent successfully' });
    } catch (error) {
        // provide error information in case there is any and send corresponding response
        console.error('Error sending email:', error);
        res.status(500).json({ error: 'Error sending email' });
    }
});

// bind and listen for connections on the specified host and port
app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

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 see how to do it using the Mailtrap official Node.js client.

Test Your Emails Now

Sending an email with the official Mailtrap Node.js client

Mailtrap’s NPM package helps you integrate with official Mailtrap API without too much coding.

In this section, we’ll rework the server-side script and leverage the API integration instead of the SMTP. 

Basically, we’re replacing the Nodemailer part of the server scrip with Mailtrap official Node.js client. And, here’s how to do it.

Step 1 – Install the official client and remove nodemailer.

Use yarn or npm, here are the snippets.

npm install mailtrap
npm uninstall nodemailer
yarn add mailtrap
yarn remove nodemailer

Step 2 – Update the .env, and only keep what’s listed below. The rest of the .env variables aren’t needed anymore.

PORT=3001
MAILTRAP_TOKEN=
SENDER_EMAIL=<yourmail@domainInMailtrap.com>
RECIPIENT_EMAIL=
CORS_ORIGIN=

Step 3 – Import the ‘MailtrapClient’ and remove nodemailer import.

Copy-paste the snippet below to the top of the server script to import the ‘MailtrapClient’.

const { MailtrapClient } = require("mailtrap");
// remove this line below
const nodemailer = require('nodemailer');

Step 4 – Initialize the ‘MailtrapClient’.

After initializing your Express app and the port const, initialize the Mailtrap client with the required token and set up the sender information from environment variable.

const client = new MailtrapClient({ token: process.env.MAILTRAP_TOKEN });
const sender = { name: 'Your Application', email: process.env.SENDER_EMAIL };

Step 5 – Modify the ‘sendmail’ endpoint.

Here, we’ll be replacing the logic within the ‘/sendmail’ endpoint with the Mailtrap SDK sending logic. The snippet also includes extra functionalities for html template, attachments, and more.

// define send endpoint, which will send emails and response with the corresponding status
app.post('/send', upload.single('file'), async (req, res) => {
try {
const { name, subject, email, message } = req.body;


// extra backend validation
if (!name || !subject || !email || !message) {
return res.status(400).json({ error: 'Missing required fields' });
}


// store attachment if provided
const attachmentData = req.file ? {
filename: req.file.originalname,
content: req.file.buffer
} : null;


// replace placeholders in the email template with received data
const emailHtml = replacePlaceholders(templateContent, { name, subject, email, message });


// use the client we created earlier to send an email with required params
client.send({
from: sender,
to: [{ email: process.env.RECIPIENT_EMAIL }],
subject: `New message from ${name} with subject ${subject}`,
text: `New message\n\nSubject: ${subject}\nFrom: ${name}\nEmail: ${email}\n\nMessage:\n\n${message}`,
html: emailHtml,
attachments: attachmentData ? [attachmentData] : [],
}).then((result) => {
console.log('Email sent...', 'Message ids: ' + result.message_ids);
res.status(200).json({ message: 'Email sent successfully' });
}).catch((error) => {
console.error('Error sending email:', error);
res.status(500).json({ error: 'Error sending email' });
})
} catch (error) {
console.error('Error sending email:', error);
res.status(500).json({ error: 'Error sending email' });
}
});

Here, we’re using the ‘client.send’ method from the Mailtrap SDK to send the email, and we’re passing the email details from the ‘user’ object received in the request.

Check what the final script may look like. The below is the full code for server.js.

const dotenv = require('dotenv');
const express = require('express');
const bodyparser = require('body-parser');
const { MailtrapClient } = require('mailtrap');
const fs = require('fs');
const cors = require('cors');
const multer = require('multer');


dotenv.config();


const app = express();
const port = process.env.PORT || 3000;
const client = new MailtrapClient({ token: process.env.MAILTRAP_TOKEN });
const sender = { name: 'Your Application', email: process.env.SENDER_EMAIL };


app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());


const corsOptions = {
origin: process.env.CORS_ORIGIN,
optionSuccessStatus: 200
};


app.use(cors(corsOptions));


const templatePath = 'email-template.html';
const templateContent = fs.readFileSync(templatePath, 'utf8');


function replacePlaceholders(html, data) {
for (const key in data) {
if (data.hasOwnProperty(key)) {
const placeholder = `{{${key}}}`;
html = html.replace(new RegExp(placeholder, 'g'), data[key]);
}
}


return html;
}


const storage = multer.memoryStorage();
const upload = multer({ storage: storage });


// define send endpoint, which will send emails and response with the corresponding status
app.post('/send', upload.single('file'), async (req, res) => {
try {
const { name, subject, email, message } = req.body;


// extra backend validation
if (!name || !subject || !email || !message) {
return res.status(400).json({ error: 'Missing required fields' });
}


// store attachment if provided
const attachmentData = req.file ? {
filename: req.file.originalname,
content: req.file.buffer
} : null;


// replace placeholders in the email template with received data
const emailHtml = replacePlaceholders(templateContent, { name, subject, email, message });


// use the client we created earlier to send an email with required params
client.send({
from: sender,
to: [{ email: process.env.RECIPIENT_EMAIL }],
subject: `New message from ${name} with subject ${subject}`,
text: `New message\n\nSubject: ${subject}\nFrom: ${name}\nEmail: ${email}\n\nMessage:\n\n${message}`,
html: emailHtml,
attachments: attachmentData ? [attachmentData] : [],
}).then((result) => {
console.log('Email sent...', 'Message ids: ' + result.message_ids);
res.status(200).json({ message: 'Email sent successfully' });
}).catch((error) => {
console.error('Error sending email:', error);
res.status(500).json({ error: 'Error sending email' });
})
} catch (error) {
console.error('Error sending email:', error);
res.status(500).json({ error: 'Error sending email' });
}
});


app.listen(port, ()=>{
console.log(`Server is running on port ${port}`);
});

Key notes on using Mailtrap’s NPM package

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

Note: You’d want to remove previous unnecessary dependencies using the npm uninstall.

Step 2: Update package.json and dd type module below “main”.

"type": "module",

Step 3: Convert your imports to the ES imports.

import dotenv from 'dotenv';
import express from 'express';
import bodyParser from 'body-parser';
import fs from 'fs';
import cors from 'cors';
import multer from 'multer';
import { SMTPClient } from 'emailjs';

Step 4: Update the .env file only with the required variables.

PORT=3001
MAILTRAP_USER=
MAILTRAP_PASS=
SMTP_HOST=live.smtp.mailtrap.io
SMTP_PORT=2525
SENDER_EMAIL=
RECIPIENT_EMAIL=
CORS_ORIGIN=

Notes on first four steps:

Step 5: Add a new method. 

Open your methods file and add a reference to emailjs using the import function. 

import { SMTPClient } from 'emailjs';

Step 6: Update the previous route with emailJS required settings.

app.post('/send', upload.single('file'), async (req, res) => {
try {
const { name, subject, email, message } = req.body;


if (!name || !subject || !email || !message) {
return res.status(400).json({ error: 'Missing required fields' });
}


const attachmentData = req.file ? {
name: req.file.originalname,
data: req.file.buffer
} : null;


const emailHtml = replacePlaceholders(templateContent, { name, subject, email, message });


const client = new SMTPClient({
user: process.env.MAILTRAP_USER,
password: process.env.MAILTRAP_PASS,
host: process.env.SMTP_HOST,
port: process.env.SMTP_PORT,
tls: true
});


const mailOptions = {
from: process.env.SENDER_EMAIL,
to: process.env.RECIPIENT_EMAIL,
cc: 'secondRecipient@example.com',
subject: `New message from ${name} with subject ${subject}`,
text: `New message\n\nSubject: ${subject}\nFrom: ${name}\nEmail: ${email}\n\nMessage:\n\n${message}`,
attachment: [
{ data: emailHtml, alternative: true },
attachmentData ? attachmentData : undefined
].filter(Boolean)
}


const newEmail = await client.sendAsync(mailOptions);


console.log('Email sent', newEmail.header['message-id']);
res.status(200).json({ message: 'Email sent successfully' });
} catch (error) {
console.error('Error sending email:', error);
res.status(500).json({ error: 'Error sending email' });
}
});

Run your backend by executing node server.js or juse the npm start command since it’s the main entrypoint.

Sending an email with attachments using native nodejs https request to Mailtrap API

The package looks as shown in the script below. There’s no extra dependency besides the body-parser, cors, dotenv, express, and multer.

{
  "name": "nodejs-native-api",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.20.2",
    "cors": "^2.8.5",
    "dotenv": "^16.3.1",
    "express": "^4.18.2",
    "multer": "^1.4.5-lts.1"
  }
}

Keep in mind that we use the same email-template.html in all the examples. We need to update the .env here again and remove the unnecessary variables, then, of course, add the required ones.

Here are the required variables in .env:

PORT=3001
MAILTRAP_API_TOKEN=
MAILTRAP_API_HOSTNAME=send.api.mailtrap.io
SENDER_EMAIL=
RECIPIENT_EMAIL=
CORS_ORIGIN=

Thereon, you need to import the native https request module of nodejs. No need to add it in package.json since it’s available by default:

const https = require('https');

Finally, proceed to update the function route for POST http requests (the rest of he code is the same as in other examples).

app.post('/send', upload.single('file'), async (req, res) => {
    try {
        const { name, subject, email, message } = req.body;

        if (!name || !subject || !email || !message) {
            return res.status(400).json({ error: 'Missing required fields' });
        }

        const attachmentData = req.file ? {
            filename: req.file.originalname,
            content: req.file.buffer.toString('base64')
        } : null;

        const emailHtml = replacePlaceholders(templateContent, { name, subject, email, message });

        const options = {
            method: 'POST',
            hostname: process.env.MAILTRAP_API_HOSTNAME,
            path: '/api/send',
            headers: {
                'Content-Type': 'application/json',
                Accept: 'application/json',
                'Api-Token': process.env.MAILTRAP_API_TOKEN
            }
        };

        const mailPayload = {
            to: [{ email: process.env.RECIPIENT_EMAIL }],
            from: { email: process.env.SENDER_EMAIL, name: 'Your App Name' },
            subject: `New message from ${name} with subject ${subject}`,
            text: `New message\n\nSubject: ${subject}\nFrom: ${name}\nEmail: ${email}\n\nMessage:\n\n${message}`,
            html: emailHtml,
            attachments: attachmentData ? [attachmentData] : []
        }

        const mailReq = https.request(options, function (mailtrapRes) {
            const chunks = [];

            mailtrapRes.on('data', function (chunk) {
                chunks.push(chunk);
            });

            mailtrapRes.on('end', function () {
                const body = Buffer.concat(chunks);
                const response = JSON.parse(body.toString());

                if (mailtrapRes.statusCode === 200) {
                    console.log('Email sent:', response.message_ids);
                    res.status(200).json({ message: 'Email sent successfully' });
                } else {
                    console.error('Error sending email:', response.errors);
                    res.status(mailtrapRes.statusCode).json(response.errors);
                }
            });
        });

        mailReq.on('error', function (response) {
            console.error('Error sending email:', response);
            res.status(500).json(response.errors);
        });

        mailReq.write(JSON.stringify(mailPayload));
        mailReq.end();
    } catch (error) {
        console.error('Non-API Error:', error);
        res.status(500).json({ error: 'Non-aPI Error' });
    }
});

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, you’ll create an Angular contact form with an attachment. Also, you need to create a service to send a request to the backend. And that’s what we’ll start with.

Step 1: Create the service.

/src/app/email.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class EmailService {

  constructor(private http: HttpClient) { }

  sendEmail(emailData: any) {
    const endpoint = 'http://localhost:3001/send';

    return this.http.post(endpoint, emailData, { observe: 'response' });
  }
}

Step 2: Update imports and providers.

/src/app/app.module.ts

Add “ReactiveFormsModule” and “HttpClientModule” in imports.
Add “EmailService” in providers.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { EmailService } from './email.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule,
    HttpClientModule
  ],
  providers: [EmailService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 3: Add bootstrap cdn to index.html in the head for utility classes.

/src/index.html

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">

Step 4: Create form logic in app.components.ts.

import { Component } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { Validators } from '@angular/forms';
import { EmailService } from './email.service';
import { HttpResponse } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Angular Contact Form';
  contactForm: FormGroup;
  emailPattern = "^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$";
  successMessage: string = '';
  showForm: boolean = true;
  selectedFile: File | null = null;

  constructor(private fb: FormBuilder, private emailService: EmailService) {
    this.contactForm = this.fb.group({
      name: ['', Validators.required],
      subject: ['', Validators.required],
      email: ['', [Validators.required, Validators.pattern(this.emailPattern)]],
      message: ['', Validators.required],
      file: ['']
    })
  }

  onSubmit() {
    if (this.contactForm.valid) {
      const formValues = this.contactForm.value;
      console.log('Form submitted with values:', formValues);

      const formData = new FormData();
      formData.append('name', formValues.name);
      formData.append('subject', formValues.subject);
      formData.append('email', formValues.email);
      formData.append('message', formValues.message);
      if (this.selectedFile) {
        formData.append('file', this.selectedFile, this.selectedFile.name);
      }

      this.emailService.sendEmail(formData).subscribe({
        next: (response: HttpResponse<any>) => {
          if (response.ok) {
            this.successMessage = response.body.message;
            this.showForm = false;
            this.clearSuccessMessage();
            this.selectedFile = null;
            this.contactForm.reset();
          }
        },
        error: (error: any) => {
          console.error('Error sending email:', error);
        }
      });

    } else {
      // Form is invalid, display error messages
      // Additional validation logic or user feedback here
    }
  }

  onFileSelected(event: any) {
    this.selectedFile = event.target.files[0];
  }

  clearSuccessMessage() {
    setTimeout(() => {
      this.successMessage = '';
      this.showForm = true;
    }, 5000);
  }

  get name() {
    return this.contactForm.get('name');
  }

  get subject() {
    return this.contactForm.get('subject');
  }

  get email() {
    return this.contactForm.get('email');
  }

  get message() {
    return this.contactForm.get('message');
  }

}

Step 5: Create form layout in app.component.html.

<div class="container-fluid">
  <div class="row justify-content-center align-items-center min-vh-100">
    <div class="col-md-4">
      <form *ngIf="showForm" [formGroup]="contactForm" (ngSubmit)="onSubmit()" enctype="multipart/form-data">
        <h2 class="mb-4">{{title}}</h2>

        <div class="form-group mb-3">
          <label for="name">Name</label>
          <input type="text" [ngClass]="{'is-invalid': name?.invalid && (name?.touched || name?.dirty)}"
            class="form-control" id="name" formControlName="name" placeholder="Your Name">
          <div *ngIf="name?.invalid && (name?.touched || name?.dirty)">
            <small *ngIf="name?.errors?.['required']" class="text-danger">Name is required</small>
          </div>
        </div>

        <div class="form-group mb-3">
          <label for="subject">Subject</label>
          <input type="text" name="subject" id="subject" class="form-control" formControlName="subject"
            placeholder="Subject" [ngClass]="{'is-invalid': subject?.invalid && (subject?.touched || subject?.dirty)}">
          <div *ngIf="subject?.invalid && (subject?.touched || subject?.dirty)">
            <small *ngIf="subject?.errors?.['required']" class="text-danger">Subject is required</small>
          </div>
        </div>

        <div class="form-group mb-3">
          <label for="email">Email</label>
          <input type="email" name="email" id="email" formControlName="email" placeholder="youremail@example.com"
            [ngClass]="{'is-invalid': email?.invalid && (email?.touched && email?.dirty)}" class="form-control">
          <div *ngIf="email?.invalid && (email?.touched || email?.dirty)">
            <small *ngIf="email?.errors?.['required']" class="text-danger">Email is required</small>
            <small *ngIf="email?.errors?.['pattern']" class="text-danger">Please provide a valid email address</small>
          </div>
        </div>

        <div class="form-group mb-3">
          <label for="message">Message</label>
          <textarea name="message" id="message" rows="4" class="form-control" formControlName="message"
            [ngClass]="{'is-invalid': message?.invalid && (message?.touched || message?.dirty)}"></textarea>
          <div *ngIf="message?.invalid && (message?.touched || message?.dirty)">
            <small *ngIf="message?.errors?.['required']" class="text-danger">Message is required</small>
          </div>
        </div>

        <div class="form-group mb-3">
          <label for="file">Attachment (PDF, JPG, PNG only)</label>
          <input type="file" class="form-control" id="file" formControlName="file" accept=".pdf, .jpg, .jpeg, .png"
            (change)="onFileSelected($event)">
        </div>

        <div class="d-flex justify-content-end">
          <button type="submit" class="btn btn-primary mt-3" [disabled]="!contactForm.valid">Send email</button>
        </div>
      </form>
      <div *ngIf="!showForm" class="alert alert-success">
        {{successMessage}}
      </div>
    </div>
  </div>
</div>

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.

Try Mailtrap for Free

Here’s what you should do:

var transport = nodemailer.createTransport({
  host: "smtp.mailtrap.io",
  port: 2525,
  auth: {
    user: "94b784b5970edf",
    pass: "01a5d515011f6e"
  }
});

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

Along with Email Sandbox, an email testing solution, Mailtrap Email Deliverability Platform comes with an Email API.

The end-to-end sending solution designed and built by engineers for engineers helps boost deliverability, does IP auto warm-up, provides suppression lists, untangles the troubleshooting process, and so much more.

Exit mobile version