0% found this document useful (0 votes)
8 views29 pages

Full Manual - Scripting Language Lab

The document outlines various programming exercises for students at Government Polytechnic College, focusing on PHP and web development. It includes tasks such as implementing string and array functions, creating an HTML form for student biodata, developing a simple application for displaying student results, creating a login page with validation, and disabling right-click options using jQuery. Each exercise provides an aim, algorithm, and example code to guide students in their learning process.

Uploaded by

keerthi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views29 pages

Full Manual - Scripting Language Lab

The document outlines various programming exercises for students at Government Polytechnic College, focusing on PHP and web development. It includes tasks such as implementing string and array functions, creating an HTML form for student biodata, developing a simple application for displaying student results, creating a login page with validation, and disabling right-click options using jQuery. Each exercise provides an aim, algorithm, and example code to guide students in their learning process.

Uploaded by

keerthi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

128 – GOVERNMENT POLYTECHNIC COLLEGE

Arakandanallur, Villupuram District.

Department of Computer Engineering

1052234640 - SCRIPTING LANGUAGES


(2023 REGULATION)
II Year / IVth Semester

Prepared By,
Mr.Daison Raj A, M.E.,
Lecturer,
Department of Computer Engineering,
128 – Government Polytechnic College,
Villupuram.

1
Ex. No. 1
Write PHP code to implement any five string and array functions
Date:

Aim:

To implement five string and array functions in PHP and demonstrate their usage.

Algorithm:

1. Start.
2. Initialize sample strings and arrays for demonstration.
3. Implement and demonstrate the following string functions:
o strlen(): Calculate the length of a string.
o str_replace(): Replace a substring in a string.
4. Implement and demonstrate the following array functions:
o array_push(): Add elements to the end of an array.
o array_merge(): Merge two or more arrays.
o array_unique(): Remove duplicate values from an array.
5. Print the results of each function.
6. Stop.

Program:

<?php
// String Functions
echo "String Functions:\n";
echo "<br>";
// 1. strlen() - Calculate the length of a string
$string = "Hello, World!";
echo "1. Length of string '$string': " . strlen($string) . "\n";
echo "<br>";
// 2. str_replace() - Replace a substring in a string
$replacedString = str_replace("World", "PHP", $string);
echo "2. Replaced String: $replacedString\n";
echo "<br>"; echo "<br>";
echo "\nArray Functions:\n";
echo "<br>";
// Array Functions
// 3. array_push() - Add elements to the end of an array
$array = [1, 2, 3];
array_push($array, 4, 5);
echo "3. Array after pushing elements: " . implode(", ", $array) . "\n";
echo "<br>";

2
// 4. array_merge() - Merge two or more arrays
$array1 = ["a", "b"];
$array2 = ["c", "d"];
$mergedArray = array_merge($array1, $array2);
echo "4. Merged Array: " . implode(", ", $mergedArray) . "\n";
echo "<br>";
// 5. array_unique() - Remove duplicate values from an array
$arrayWithDuplicates = [1, 2, 2, 3, 4, 4, 5];
$uniqueArray = array_unique($arrayWithDuplicates);
echo "5. Unique Array: " . implode(", ", $uniqueArray) . "\n";
echo "<br>";
?>

Output:

Result:
Thus, the implementation and usage of five string and array functions in PHP were
successfully demonstrated.

3
Ex. No. 2 Design the HTML form to collect student biodata and SSLC Mark, Process the
Date: collected data in the PHP and Find Total and Average for Mark.

Aim:

To design an HTML form to collect student biodata and SSLC marks, process the collected
data in PHP, and calculate the total and average marks.

Algorithm:

1. Start.
2. Create an HTML form to collect the following details:
o Student Name
o Age
o SSLC Marks for five subjects.
3. Submit the form data to a PHP script for processing.
4. In the PHP script:
o Retrieve form data using $_POST.
o Calculate the total of the five marks.
o Calculate the average.
5. Display the collected details, total marks, and average marks.
6. Stop.

Program:

//input_Form.html

<!DOCTYPE html>
<html>
<head>
<title>Student Biodata and Marks</title>
</head>
<body>
<h1>Student Biodata and SSLC Marks</h1>
<form action="process.php" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>

<label for="age">Age:</label>
<input type="number" id="age" name="age" required><br><br>

<h3>SSLC Marks:</h3>
<label for="mark1">Subject 1:</label>
<input type="number" id="mark1" name="mark1" required><br><br>

<label for="mark2">Subject 2:</label>


<input type="number" id="mark2" name="mark2" required><br><br>

4
<label for="mark3">Subject 3:</label>
<input type="number" id="mark3" name="mark3" required><br><br>

<label for="mark4">Subject 4:</label>


<input type="number" id="mark4" name="mark4" required><br><br>

<label for="mark5">Subject 5:</label>


<input type="number" id="mark5" name="mark5" required><br><br>

<button type="submit">Submit</button>
</form>
</body>
</html>

//process.php

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Collecting form data
$name = $_POST['name'];
$age = $_POST['age'];
$marks = [
$_POST['mark1'],
$_POST['mark2'],
$_POST['mark3'],
$_POST['mark4'],
$_POST['mark5']
];

// Calculate total and average


$total = array_sum($marks);
$average = $total / count($marks);

// Displaying the results


echo "<h1>Student Biodata</h1>";
echo "<p>Name: $name</p>";
echo "<p>Age: $age</p>";
echo "<h3>Marks:</h3>";
foreach ($marks as $key => $mark) {
echo "<p>Subject " . ($key + 1) . ": $mark</p>";
}
echo "<h3>Results:</h3>";
echo "<p>Total Marks: $total</p>";
echo "<p>Average Marks: $average</p>";
}
?>

5
Output:

Result:
Thus the program collected student biodata and SSLC Mark and processed the collected data in
the PHP execution and finally found Total and Average for Mark successfully.

6
Ex. No. 3 Develop the simple application which display result of the student by getting
Date: register number as user input( assume student marks are already available in
the database)

Aim:
To develop a simple application that displays the result of a student by getting the register number as
user input, assuming the student marks are already available in the database.

Algorithm:

1. Start
2. Connect to the database: Establish a connection to the database containing the student marks table.
3. Get input from the user: Prompt the user to enter the register number of the student.
4. Query the database: Execute a query to fetch the student's details and marks using the entered register
number.
5. Calculate the result:
o If marks in all subjects are greater than or equal to the passing marks, the result is "Pass."
o If any subject marks are below the passing marks, the result is "Fail."
6. Display the result: Show the student’s name, marks, and result on the console or webpage.
7. Handle errors:
o If the entered register number does not exist, display an appropriate error message.
o Handle any database connection or query errors.
8. Close the database connection.
9. Stop.

SQL Script to Create and Populate the Table:


-- Create Database
CREATE DATABASE student_db;

-- Use the Database


USE student_db;

-- Create Table student_marks


CREATE TABLE student_marks (
register_number VARCHAR(10) PRIMARY KEY,
name VARCHAR(50) NOT NULL,
subject1 INT(3) NOT NULL,
subject2 INT(3) NOT NULL,
subject3 INT(3) NOT NULL,
subject4 INT(3) NOT NULL,
subject5 INT(3) NOT NULL
);

-- Insert Sample Data


INSERT INTO student_marks (register_number, name, subject1, subject2, subject3, subject4,
subject5) VALUES ('101', 'John Doe', 75, 80, 65, 50, 45), ('102', 'Jane Smith', 35, 40, 55, 60, 70),
('103', 'Alice Johnson', 85, 90, 95, 88, 92), ('104', 'Bob Brown', 50, 30, 45, 40, 55),
('105', 'Charlie Davis', 65, 70, 60, 80, 75);

7
Program: (PHP with MySQL)

//Process2.php
<?php
// Database connection details
$servername = "localhost";
$username = "root";
$password = "daison"; // Replace with your MySQL password if set
$dbname = "student_db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Initialize variables
$register_number = "";
$output = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$register_number = $_POST['register_number'];

// Fetch student details and marks from the database


$sql = "SELECT name, subject1, subject2, subject3, subject4, subject5 FROM student_marks
WHERE register_number = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $register_number);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
// Fetch the result row
$row = $result->fetch_assoc();
$name = $row['name'];
$marks = [$row['subject1'], $row['subject2'], $row['subject3'], $row['subject4'], $row['subject5']];
$passing_marks = 40;

// Determine result
$result_status = "Pass";
foreach ($marks as $mark) {
if ($mark < $passing_marks) {
$result_status = "Fail";
break;
}
}

8
// Format the output
$output = "Student Name: $name<br>";
$output .= "Marks: " . implode(", ", $marks) . "<br>";
$output .= "Result: $result_status";
} else {
$output = "Error: Register number not found.";
}

// Close the statement


$stmt->close();
}

// Close the connection


$conn->close();
?>

<!DOCTYPE html>
<html>
<head>
<title>Student Result</title>
</head>
<body>
<h2>Enter Register Number</h2>
<form method="POST" action="">
<label for="register_number">Register Number:</label>
<input type="text" id="register_number" name="register_number" required>
<button type="submit">Submit</button>
</form>
<h3>Result:</h3>
<p><?php echo $output; ?></p>
</body>
</html>

Output:

9
Result:
Thus, a simple application was developed to display the result of a student by fetching details
from the database using the register number provided as user input.

10
Ex. No. 4 Develop the simple login page, which validates the username, and password
Date: (assume username, password and student_name are stored in the database). If
username and password are correct, the page should redirect to
Welcome.phpfile and display the student_name in that page. If username or
password is incorrect page should remain in login page itself.

Aim

To develop a simple login page that validates the username and password from the database. If correct,
it redirects to a Welcome.php page to display the student name. If incorrect, it remains on the login
page.

Algorithm

1. Create the Database


o Create a database table users with the fields username, password, and student_name.
2. Design the Login Page (HTML)
o Create an HTML form with fields for username and password.
o Add a submit button.
3. Develop the Login Validation Logic (PHP)
o Connect to the database using mysqli or PDO.
o Fetch the username and password entered by the user.
o Query the database to check if the credentials are valid.
o If valid:
 Redirect to Welcome.php with the student_name.
o If invalid:
 Display an error message and remain on the login page.
4. Create the Welcome Page (PHP)
o Retrieve the student_name passed from the login script.
o Display the name on the page.
5. Test the Program
o Check the functionality for both correct and incorrect credentials.

Program

1. Database Script (MySQL)

CREATE DATABASE student_portal;

USE student_portal;

CREATE TABLE users (


id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,

11
password VARCHAR(50) NOT NULL,
student_name VARCHAR(100) NOT NULL
);

INSERT INTO users (username, password, student_name)


VALUES ('user1', 'pass123', 'John Doe'), ('user2', 'mypassword', 'Jane Smith'),
('admin', 'admin123', 'Admin User');

2. Login Page (login.php)

<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
<form method="POST" action="validate.php">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>

3. Login Validation Logic (validate.php)

<?php
// Database connection
$conn = new mysqli('localhost', 'root', '', 'student_portal');

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Fetch input
$username = $_POST['username'];
$password = $_POST['password'];

// Query to validate user


$sql = "SELECT student_name FROM users WHERE username = ? AND password = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$stmt->store_result();

12
if ($stmt->num_rows > 0) {
$stmt->bind_result($student_name);
$stmt->fetch();
header("Location: Welcome.php?name=" . urlencode($student_name));
exit();
} else {
echo "<p style='color:red;'>Invalid username or password. Please try again.</p>";
echo "<a href='login.php'>Back to Login</a>";
}

$stmt->close();
$conn->close();
?>

4. Welcome Page (Welcome.php)

<?php
if (!isset($_GET['name'])) {
header("Location: login.php");
exit();
}

$student_name = htmlspecialchars($_GET['name']);
?>

<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome, <?php echo $student_name; ?>!</h1>
</body>
</html>

13
Output:

14
Result:
The program successfully validates the username and password, redirects to the welcome page
with the student_name on successful login, and remains on the login page with an error message on
failure.

15
Ex. No. 5
Write the code to disable right-click option in the webpage using the jQuery
Date:

Aim

To create a script using jQuery that disables the right-click option on a webpage to prevent
users from accessing the context menu.

Algorithm

1. Start
2. Include Required Libraries:
o Include the jQuery library in the HTML file to use its features.
3. Write the HTML Structure:
o Create a basic HTML structure with content to demonstrate the feature.
4. Add the jQuery Script:
o Use the $(document).ready() function to ensure the script runs after the DOM is fully
loaded.
o Bind an event handler for the contextmenu event on the document object.
o Prevent the default behavior of the contextmenu event using the event.preventDefault()
method.
o Optionally, display a custom message to the user if they attempt to right-click.
5. Test the Code:
o Open the webpage in a browser and attempt to right-click to verify that the context
menu is disabled.
6. End

Program

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Disable Right Click</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 100px;
}
.notice {
color: red;

16
font-weight: bold;
}
</style>
</head>
<body>
<h1>Right-Click Disabled</h1>
<p>Try to right-click anywhere on this page.</p>
<p class="notice">Note: Right-clicking is disabled using jQuery.</p>

<script>
$(document).ready(function () {
// Disable the right-click context menu
$(document).on("contextmenu", function (e) {
e.preventDefault();
alert("Right-click is disabled on this page!");
});
});
</script>
</body>
</html>

Output:

Result:

The program successfully disables the right-click option on the webpage using jQuery, and an
alert message is shown whenever a right-click is attempted.

17
Ex. No. 6 Develop the simple application which display details of the college by getting
Date: college code as input using AJAX without reloading the page (assume college
details like code, name, courses_offered, address, hostel facility, etc., are
already available in the database)

Aim

To develop a simple web application that displays details of a college by taking the college
code as input using AJAX, without reloading the page. The application retrieves details such as
college code, name, courses offered, address, and hostel facility from a database.

Algorithm

1. Setup the Environment:


o Install and configure a server (e.g., Apache or Nginx).
o Create a database table with details of colleges.
2. Create the Database:
o Define a table named college_details with the following fields: college_code,
college_name, courses_offered, address, hostel_facility.
o Populate the table with sample data.
3. Create the Backend (PHP):
o Write a PHP script to handle AJAX requests and fetch college details from the database
based on the provided college code.
o Return the details as a JSON response.
4. Design the Frontend (HTML, CSS, JavaScript):
o Create an input field for entering the college code.
o Add a button to trigger the AJAX call.
o Create a section to display the fetched college details.
5. Implement AJAX Logic (JavaScript):
o Use XMLHttpRequest or the fetch API to send a request to the server with the entered
college code.
o Parse the JSON response and dynamically update the page to display the details.
6. Test the Application:
o Enter various college codes and verify that the correct details are displayed without
reloading the page.

Program

Database Schema:

create database college;


use college;

18
CREATE TABLE college_details (
college_code VARCHAR(10) PRIMARY KEY,
college_name VARCHAR(100),
courses_offered TEXT,
address TEXT,
hostel_facility VARCHAR(10)
);

INSERT INTO college_details (college_code, college_name, courses_offered, address, hostel_facility)


VALUES
('C101', 'ABC Engineering College', 'B.Tech, M.Tech, MBA', '123 Main Street, City', 'Yes'),
('C102', 'XYZ Arts College', 'BA, MA, BBA', '456 Side Avenue, Town', 'No');

Backend (PHP): //get_college_details.php

<?php
$servername = "localhost";
$username = "root";
$password = "daison";
$dbname = "college";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

if (isset($_GET['college_code'])) {
$college_code = $conn->real_escape_string($_GET['college_code']);
$sql = "SELECT * FROM college_details WHERE college_code = '$college_code'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
echo json_encode($result->fetch_assoc());
} else {
echo json_encode(["error" => "College not found"]);
}
}

$conn->close();
?>

Frontend (HTML + JavaScript): // index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">

19
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>College Details</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
input, button { margin: 10px 0; padding: 10px; font-size: 16px; }
.result { margin-top: 20px; padding: 10px; border: 1px solid #ccc; background: #f9f9f9; }
</style>
</head>
<body>
<h1>Find College Details</h1>
<label for="college_code">Enter College Code:</label>
<input type="text" id="college_code" placeholder="e.g., C101">
<button onclick="getCollegeDetails()">Get Details</button>

<div class="result" id="result"></div>

<script>
function getCollegeDetails() {
const collegeCode = document.getElementById('college_code').value;
const resultDiv = document.getElementById('result');

if (!collegeCode) {
resultDiv.innerHTML = "<p>Please enter a college code.</p>";
return;
}

fetch(`get_college_details.php?college_code=${collegeCode}`)
.then(response => response.json())
.then(data => {
if (data.error) {
resultDiv.innerHTML = `<p>${data.error}</p>`;
} else {
resultDiv.innerHTML = `
<h3>${data.college_name}</h3>
<p><strong>Code:</strong> ${data.college_code}</p>
<p><strong>Courses Offered:</strong> ${data.courses_offered}</p>
<p><strong>Address:</strong> ${data.address}</p>
<p><strong>Hostel Facility:</strong> ${data.hostel_facility}</p>
`;
}
})
.catch(error => {
resultDiv.innerHTML = `<p>Error fetching details: ${error.message}</p>`;
});
}
</script>
</body>
</html>

20
Output

Result:

The simple web application successfully displays college details by taking the college code as
input using AJAX, without reloading the page.

21
Ex. No. 7
Develop the Node.js code to upload the file to server
Date:

Aim

To develop a Node.js program that uploads a file to a server, allowing users to transfer files securely
and efficiently.

Algorithm

1. Set up the environment


o Install Node.js and npm on the system.
o Create a new project directory and initialize a Node.js project using npm init.
o Install required modules: express for server handling and multer for file uploads.
2. Create necessary files
o Create a file app.js for the Node.js code.
o Create a directory uploads to store uploaded files.
3. Import required modules
o Import express and multer.
4. Configure file upload handling
o Use multer to configure the destination directory and file naming.
o Set up middleware to handle multipart form data.
5. Create an upload endpoint
o Set up an HTTP POST route /upload to accept file uploads.
o Handle the uploaded file using the configured multer middleware.
6. Start the server
o Use express to start the server on a specified port.
7. Test the application
o Use a frontend or API testing tool (like Postman) to upload a file.
o Verify the file is uploaded to the uploads directory.

Program
//File: app.js
const express = require('express');
const multer = require('multer');
const path = require('path');

const app = express();

// Configure multer for file upload


const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
cb(null, `${Date.now()}-${file.originalname}`);
}

22
});

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

// Serve HTML form for file upload


app.get('/', (req, res) => {
res.send(`
<h1>File Upload</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit">Upload</button>
</form>
`);
});

// Endpoint to handle file upload


app.post('/upload', upload.single('file'), (req, res) => {
if (!req.file) {
return res.status(400).send('No file uploaded.');
}
res.send(`File uploaded successfully: ${req.file.filename}`);
});

// Start the server


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

Steps to Run the Program with XAMPP Installed

1. Set Up Node.js

Ensure Node.js is installed on your system. If not, download and install it.
(https://nodejs.org/en)
 Initialize your Node.js project:
npm init -y
 Install the required packages:
npm install express multer
2. Prepare the Application

 Place your app.js file (Node.js program) in a separate directory outside the XAMPP htdocs
folder. For example, C:\NodeFileUpload.
 Create an uploads directory inside this folder to store the uploaded files.

3. Run the Node.js Application

 Open a terminal or command prompt.


23
 Navigate to the directory where your app.js file is located:
cd C:\NodeFileUpload
 Start the Node.js application:
node app.js
 The server will start and display a message like:
Server running at http://localhost:3000
4. Access the Application
 Open a browser and visit: http://localhost:3000/.
 You will see the file upload form.
5. Upload a File
 Use the form to upload a file.
 Check the uploads directory in your project folder (C:\NodeFileUpload\uploads) to verify the
uploaded file.

24
Output
1. Frontend Form (accessed via browser)
o URL: http://localhost:3000/
o Form appears with an upload button.
2. File Upload Success Message
o Upload a file named example.txt.
o Output:
File uploaded successfully: 1686753456789-example.txt
3. Uploaded File Stored
o File stored in uploads directory with a unique timestamped filename.

Result:

The Node.js program to upload a file to the server was successfully developed and tested. The
file is uploaded and stored in the server's uploads directory with a unique name.

25
Ex. No. 8
Develop the Node.js code to send an email
Date:

Aim

To develop a Node.js application that sends an email using the nodemailer module.

Algorithm

1. Install Node.js and Initialize Project


o Install Node.js from its official website.
o Create a new folder for the project and navigate to it in the terminal.
o Run npm init -y to create a package.json file.
2. Install Required Modules
o Use npm install nodemailer to install the Nodemailer package.
3. Create the Script
o Create a JavaScript file, e.g., sendEmail.js.
4. Import Nodemailer
o Import the nodemailer module in the script.
5. Configure Email Settings
o Use the nodemailer.createTransport method to configure the SMTP (Simple Mail
Transfer Protocol) settings with details like the service provider, email, and password.
6. Define Email Content
o Create an email object with properties like from, to, subject, and text.
7. Send the Email
o Use the sendMail method to send the email, and handle the success or error response.
8. Run the Program
o Execute the program using the command node sendEmail.js.
9. Verify Output
o Check the recipient's email inbox for the message.

Program

const nodemailer = require('nodemailer');

// Step 1: Create a transporter


const transporter = nodemailer.createTransport({
service: 'gmail', // Specify the email service
auth: {
user: 'ardaison@gmail.com', // Your email
pass: 'sjyl spiw cqtl qvgi' // Your email or app password (Refer Generate Password)
}
});

// Step 2: Set email options


const mailOptions = {
from: 'ardaison@gmail.com', // Sender's email
to: 'daison.2008@gmail.com', // Receiver's email
26
subject: 'Test Email from Node.js', // Subject
text: 'Hello! This is a test email sent using Node.js and Nodemailer.' // Email body
};

// Step 3: Send the email


transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error('Error occurred:', error);
} else {
console.log('Email sent successfully:', info.response);
}
});

Steps to Run Node.js with XAMPP


1. Install Node.js
 Download and install Node.js from the official Node.js website.
2. Create Your Project
 Open your XAMPP folder (e.g., C:\xampp\htdocs on Windows or /opt/lampp/htdocs on
Linux).
 Create a new folder for your Node.js project inside htdocs. For example:
C:\xampp\htdocs\node-email
 Navigate to this folder using your terminal or command prompt:
cd C:\xampp\htdocs\node-email
4. Initialize the Node.js Project
npm init -y
 This will generate a package.json file in your project folder.
5. Install Nodemailer
 Run:
npm install nodemailer
6. Create the Email Script
 In your project folder, create a file named sendEmail.js and add the program from above.
7. Run the Program
 Open your terminal or command prompt in the project directory and run the script:
node sendEmail.js
8. Verify the Output
 Check the terminal for the message indicating success or errors.
 If successful, the recipient should receive the email.

Procedure for Generate App Password:

1. Enable 2-Step Verification

 Go to your Google Account: myaccount.google.com.


 Navigate to Security in the left sidebar.

27
 Under the Signing in to Google section, ensure that 2-Step Verification is enabled. If it's not
enabled, set it up.

2. Generate an App Password (pass: 'sjyl spiw cqtl qvgi' – to be given in program)

 After enabling 2-Step Verification:


1. Go to App Passwords under the Security section.
 Direct link: https://myaccount.google.com/apppasswords.
2. Select the app (e.g., Mail) and the device (e.g., Windows Computer), then click
Generate.
3. Copy the generated 16-character password.

Output

28
Result:

The Node.js application was successfully developed to send an email. The email was sent and
verified in the recipient's inbox.

29

You might also like