Skip to content

Commit

Permalink
Merge pull request #881 from 17arindam/newsletter
Browse files Browse the repository at this point in the history
Newsletter storing in database and a email is being sent to user
  • Loading branch information
ANSHIKA-26 authored Oct 13, 2024
2 parents 3de743b + 733ab55 commit 6fb354c
Show file tree
Hide file tree
Showing 10 changed files with 187 additions and 3 deletions.
2 changes: 2 additions & 0 deletions backend/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
EMAIL_USER=your_gmail
EMAIL_PASS=your_16_digit_pass
2 changes: 1 addition & 1 deletion backend/Database.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ async function ConnectDb() {
try {
// const DatabaseConnect = process.env.DatabaseConnect;
await mongoose.connect(
"Your MongoDb Connection String" //establish database connection // mongodb+srv://username:[email protected]/DatabseName
"mongodb://localhost:27017/" //establish database connection // mongodb+srv://username:[email protected]/DatabseName
);

console.log("connected to database");
Expand Down
49 changes: 49 additions & 0 deletions backend/config/nodemailer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
require("dotenv").config();
const nodemailer = require("nodemailer");


// Create a Nodemailer transporter using SMTP
const transporter = nodemailer.createTransport({
service: "gmail", // or your preferred email service
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS,
},
});

// Function to send newsletter subscription confirmation via email
exports.sendSubscriptionConfirmation = async (email) => {
// Construct the email content
const emailText = `
Dear Customer,
Thank you for subscribing to the WordWise newsletter!
We're thrilled to welcome you to our community of passionate writers and language enthusiasts.
If you have any questions or feedback, feel free to reach out.
Best regards,
WordWise Team
`;

try {
await transporter.sendMail({
from: process.env.EMAIL_USER,
to: email,
subject: "Thank You for Subscribing!",
text: emailText,
});

} catch (error) {

if (error.code === "ECONNREFUSED") {
throw new Error(
"Failed to connect to email server. Please try again later.",
);
} else {
throw new Error(
`Failed to send subscription confirmation email: ${error.message}`,
);
}
}
};
44 changes: 44 additions & 0 deletions backend/controllers/NewsLetterController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const NewsletterEmail = require("../modal/NewsLetterModel"); // Import the Mongoose model
const { sendSubscriptionConfirmation } = require("../config/nodemailer"); // Import the mailer function

// Controller for handling newsletter subscriptions
exports.subscribeToNewsletter = async (req, res) => {
const { email } = req.body;

if (!email) {
return res.status(400).json({ error: "Email is required" });
}

try {
// Check if the email already exists in the database
const existingEmail = await NewsletterEmail.findOne({ email });
if (existingEmail) {
return res
.status(400)
.json({ error: "This email is already subscribed." });
}

// Save the email to the database
const newEmail = new NewsletterEmail({ email });
await newEmail.save();

try {
await sendSubscriptionConfirmation(email);
} catch (error) {
console.error("Error sending confirmation email:", error);
return res.status(500).json({
error:
"Subscription successful, but there was an error sending the confirmation email.",
});
}

return res.status(201).json({
message: "Subscription successful! A confirmation email has been sent.",
});
} catch (error) {
console.error("Error subscribing to newsletter:", error);
return res
.status(500)
.json({ error: "Error subscribing to the newsletter." });
}
};
20 changes: 20 additions & 0 deletions backend/modal/NewsLetterModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/* eslint-disable no-useless-escape */
const mongoose = require("mongoose");

// Define the schema for newsletter emails
const NewsletterEmailSchema = new mongoose.Schema({
email: {
type: String,
required: true,
unique: true, // Ensure no duplicate emails
trim: true,
match: [/.+\@.+\..+/, "Please enter a valid email address"], // Simple email validation
},
subscribedAt: {
type: Date,
default: Date.now, // Automatically set the date of subscription
},
});

// Export the model
module.exports = mongoose.model("NewsletterEmail", NewsletterEmailSchema);
22 changes: 22 additions & 0 deletions backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@
"dependencies": {
"body-parser": "^1.20.3",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.21.0",
"express-formidable": "^1.2.0",
"formidable": "^3.5.1",
"logger": "^0.0.1",
"mongoose": "^8.7.0",
"nodemailer": "^6.9.15"
}
Expand Down
11 changes: 10 additions & 1 deletion backend/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,16 @@ const formidable = require("express-formidable");
const fs = require("fs").promises;

const ConnectDb = require("./Database");
const { subscribeToNewsletter } = require("./controllers/NewsLetterController");

app.use(bodyParser.json());
app.use(cors());
const corsOptions = {
origin: ['http://localhost:5501', 'http://127.0.0.1:5501'],
methods: ['GET', 'POST', 'HEAD', 'OPTIONS'], // Allow POST method
credentials: true
};

app.use(cors(corsOptions));
ConnectDb();

app.post("/send-email", async (req, res) => {
Expand Down Expand Up @@ -79,6 +86,8 @@ app.post("/subscribe", async (req, res) => {
}
});

app.post('/newsletter',subscribeToNewsletter);

//create a blog Api

app.post("/post_blog", formidable(), async (req, resp) => {
Expand Down
2 changes: 1 addition & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -1347,7 +1347,7 @@ <h2>Subscribe to Our Newsletter</h2>
<input type="email" id="emailInput" placeholder="Enter your email address" required>
<div id="error-message" style="color: red; display: none;">Please include '@' in your email address.
</div>
<div id="sub"><button type="submit">Subscribe</button></div>
<button type="button" onclick="submitNewsletter()">Subscribe</button>
</form>
</div>

Expand Down
36 changes: 36 additions & 0 deletions main.js
Original file line number Diff line number Diff line change
Expand Up @@ -187,3 +187,39 @@ if (aboutSection) {
document.querySelector('#about-us').scrollIntoView({ behavior: 'smooth' });
});
}

function submitNewsletter() {
const emailInput = document.getElementById('emailInput');
const errorMessage = document.getElementById('error-message');
const email = emailInput.value;

// Simple email validation check
if (!email.includes('@')) {
errorMessage.style.display = 'block';
return;
} else {
errorMessage.style.display = 'none';
}

// Send POST request
fetch('http://127.0.0.1:3000/newsletter', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ email })
})
.then(response => {
if (response.ok) {
alert('Subscribed successfully!');
emailInput.value = ''; // Clear the input field
} else {
alert('Failed to subscribe. Please try again later.');
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred. Please try again later.');
});
}

0 comments on commit 6fb354c

Please sign in to comment.