DEV Community

Cover image for Sending email using Node.js and Nodemailer with Angular App Contact Form
Chabba Saad
Chabba Saad

Posted on

Sending email using Node.js and Nodemailer with Angular App Contact Form

today i m going to share an example of how to sent email in your angular application using nodemailer

Front-end Part

  1. Create a new Angular project using the Angular CLI:
ng new angular-email-form

Enter fullscreen mode Exit fullscreen mode
  1. Navigate into the project directory:
cd angular-email-form

Enter fullscreen mode Exit fullscreen mode
  1. Generate a new component for the contact form:
ng generate component contact-form

Enter fullscreen mode Exit fullscreen mode
  1. Open src/app/contact-form/contact-form.component.html and add the following HTML:
<div>
  <div class="contact-form-wrapper d-flex justify-content-center">
    <form (ngSubmit)="onSubmit()" class="contact-form">
      <h5 class="title">Contact us</h5>
      <p class="description">{{ "Lets talk about everything!" | translate }}
      </p>
      <div>
        <input type="text" class="form-control rounded border-white mb-3 form-input" [(ngModel)]="name" name="name" placeholder="Name" required>
      </div>
      <div>
        <input type="email" class="form-control rounded border-white mb-3 form-input" [(ngModel)]="email" name="email" placeholder="Email" required>
      </div>
      <div>
        <textarea class="form-control rounded border-white mb-3 form-text-area" [(ngModel)]="message" name="message" rows="5" cols="30" placeholder="Message" required></textarea>
      </div>
      <div class="submit-button-wrapper">
        <button type="submit">Send</button>
      </div>
    </form>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode
  1. Open src/app/contact-form/contact-form.component.ts and add the following code:
import { Component } from '@angular/core';
import { EmailService } from '../email.service';

@Component({
  selector: 'app-contact-form',
  templateUrl: './contact-form.component.html',
  styleUrls: ['./contact-form.component.css']
})
export class ContactFormComponent {
  name: string;
  email: string;
  message: string;

  constructor(private emailService: EmailService) {}

  onSubmit() {
    this.emailService.sendEmail(this.name, this.email, this.message).subscribe(
      response => {
        console.log('Email sent successfully!');
      },
      error => {
        console.log('Error sending email:', error);
      }
    );
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. Generate a new service for sending emails:
ng generate service email
Enter fullscreen mode Exit fullscreen mode
  1. Open src/app/email.service.ts and add the following code:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

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

  private emailUrl = 'http://localhost:3000/send-email'; // Replace with your backend URL

  constructor(private http: HttpClient) { }

  sendEmail(name: string, email: string, message: string) {
    const data = {
      name: name,
      email: email,
      message: message
    };
    return this.http.post(this.emailUrl, data);
  }

}
Enter fullscreen mode Exit fullscreen mode

Back-end Part

  1. Create a new Node.js project:
mkdir node-email-form
cd node-email-form
npm init
Enter fullscreen mode Exit fullscreen mode
  1. Install the required dependencies:
npm install express body-parser cors nodemailer --save

Enter fullscreen mode Exit fullscreen mode
  1. Create a new file index.js and add the following code:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const nodemailer = require('nodemailer');

const app = express();
const port = 3000;

app.use(bodyParser.json());
app.use(cors());

app.post('/send-email', (req, res) => {
  const name = req.body.name;
  const email = req.body.email;
  const message = req.body.message;

  const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      user: 'your-email-address@gmail.com', // Replace with your email address
      pass: 'your-email-password' // Replace with your email password
    }
  });

  const mailOptions = {
    from: 'your-email-address@gmail.com',
    to: 'recipient-email-address@example.com', // Replace with recipient email address
    subject: 'New Contact Form Submission',
    text: `
      Name: ${name}
      Email: ${email}
      Message: ${message}
    `
  };

  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      console.log(error);
      res.status(500).send('Error sending email');
    } else {
      console.log('Email sent:', info.response);
      res.status(200).send('Email sent successfully');
    }
  });
});

app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
});
Enter fullscreen mode Exit fullscreen mode

This code defines a new Node.js server that listens on port 3000. When a POST request is made to the /send-email endpoint, the server reads the name, email, and message fields from the request body and sends an email using the Nodemailer library.

Note that you will need to replace the user and pass fields in the transporter object with your own email address and password, and the to field in the mailOptions object with the recipient email address.

  1. Start the Node.js server:
node index.js
Enter fullscreen mode Exit fullscreen mode

Testing the Application

Start the Angular development server:

ng serve
Enter fullscreen mode Exit fullscreen mode
  1. Open your web browser and navigate to http://localhost:4200/.
  2. Fill out the contact form and click the "Send" button.
  3. Check

Top comments (1)

Collapse
 
manojmj profile image
Manojkumar

This is really fantastic. Sendgrid is best or nodemailer