How to create Angular contact form and send email

How-to-create-contact-form-and-send-email-in-angular

To create a contact form and send an email in Angular, you can use Angular forms for the front-end and a backend service (such as Node.js with Express) to handle the email sending. Below is a simplified example using Angular and a Node.js/Express backend.

Step 1: Set Up Angular Project

Assuming you have Angular CLI installed, create a new Angular project:

ng new my-email-app
cd my-email-app

Step 2: Create a Contact Form Component

Create a new component for your contact form, for example, ‘contact-form.component.ts’.

// src/app/contact-form/contact-form.component.ts
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

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

  constructor(private fb: FormBuilder) {
    this.contactForm = this.fb.group({
      name: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]],
      message: ['', Validators.required],
    });
  }

  onSubmit() {
    if (this.contactForm.valid) {
      // Implement sending email logic here
      console.log('Form submitted:', this.contactForm.value);
      // You can call a service to send the email from here
    }
  }
}

Step 3: Create Contact Form Template

Create the template file for your contact form, for example, ‘contact-form.component.html’.





Step 4: Set Up Angular Forms Module

Make sure to import ‘ReactiveFormsModule’ in your ‘AppModule’ to use reactive forms.

// src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { ContactFormComponent } from './contact-form/contact-form.component';

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

Step 5: Set Up Node.js/Express Backend

Create a simple Node.js/Express backend to handle email sending. You can use a package like nodemailer for this.

npm init -y
npm install express nodemailer

Create a file ‘server.js’:

// server.js
const express = require('express');
const nodemailer = require('nodemailer');
const bodyParser = require('body-parser');

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

app.use(bodyParser.json());

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

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

  // Set up email options
  const mailOptions = {
    from: 'your-email@gmail.com',
    to: 'recipient-email@example.com', // replace with recipient email
    subject: 'New Contact Form Submission',
    text: `Name: ${name}\nEmail: ${email}\nMessage: ${message}`,
  };

  // Send email
  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      return res.status(500).send(error.toString());
    }
    res.status(200).send('Email sent: ' + info.response);
  });
});

app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});

Step 6: Connect Angular to the Backend

Modify your Angular component to make an HTTP request to your Node.js backend.

// src/app/contact-form/contact-form.component.ts
import { HttpClient } from '@angular/common/http';

// ...

export class ContactFormComponent {
  // ...

  constructor(private fb: FormBuilder, private http: HttpClient) {
    // ...
  }

  onSubmit() {
    if (this.contactForm.valid) {
      const formData = this.contactForm.value;
      
      // Make HTTP post request to your Node.js backend
      this.http.post('http://localhost:3000/send-email', formData).subscribe(
        (response) => {
          console.log('Email sent successfully:', response);
        },
        (error) => {
          console.error('Email send failed:', error);
        }
      );
    }
  }
}

Step 7: Run Your Applications

Start your Angular development server:

ng serve

And start your Node.js/Express backend:

node server.js

Visit http://localhost:4200 in your browser and check the console for form submissions and email sending logs. Ensure that you replace the placeholder values with your actual email credentials in the server.js file and set up secure practices for handling sensitive information in a production environment.

Related Posts