today i m going to share an example of how to sent email in your angular application using nodemailer
Front-end Part
- Create a new Angular project using the Angular CLI:
ng new angular-email-form
- Navigate into the project directory:
cd angular-email-form
- Generate a new component for the contact form:
ng generate component contact-form
- 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>
- 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);
}
);
}
}
- Generate a new service for sending emails:
ng generate service email
- 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);
}
}
Back-end Part
- Create a new Node.js project:
mkdir node-email-form
cd node-email-form
npm init
- Install the required dependencies:
npm install express body-parser cors nodemailer --save
- 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}`);
});
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.
- Start the Node.js server:
node index.js
Testing the Application
Start the Angular development server:
ng serve
- Open your web browser and navigate to http://localhost:4200/.
- Fill out the contact form and click the "Send" button.
- Check
Top comments (1)
This is really fantastic. Sendgrid is best or nodemailer