Sending email using Node.js and Nodemailer with Angular App Contact Form
Tags: angular
Published: 2023-04-28 11:07:58

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:

```php
ng new angular-email-form

```
2. Navigate into the project directory:
```php
cd angular-email-form

```
3. Generate a new component for the contact form:
```php
ng generate component contact-form

```
4. Open src/app/contact-form/contact-form.component.html and add the following HTML:
```php
<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>
```
5. Open src/app/contact-form/contact-form.component.ts and add the following code:
```php
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);
      }
    );
  }
}
```
6. Generate a new service for sending emails:
```javascript
ng generate service email
```
7. Open src/app/email.service.ts and add the following code:
```php
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);
  }

}
```





**Back-end Part**

1. Create a new Node.js project:

```react
mkdir node-email-form
cd node-email-form
npm init
```

2. Install the required dependencies:

```react
npm install express body-parser cors nodemailer --save

```

3. Create a new file index.js and add the following code:

```php
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}`);
});
```

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.

4. Start the Node.js server:

```php
node index.js
```

**Testing the Application**

## Start the Angular development server:

```javascript
ng serve
```

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