You can use Nodemailer to send an email in Node.js after successfully storing a record in MongoDB.
Steps:
Install Dependencies
npm install nodemailer mongoose
Code Example
const mongoose = require('mongoose');
const nodemailer = require('nodemailer');
// MongoDB Connection
mongoose.connect('mongodb://localhost:27017/testDB', { useNewUrlParser: true, useUnifiedTopology: true });
// Define Schema & Model
const UserSchema = new mongoose.Schema({ email: String, name: String });
const User = mongoose.model('User', UserSchema);
// Nodemailer Transporter
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your-email@gmail.com',
pass: 'your-email-password'
}
});
// Function to Save Data and Send Email
async function saveUserAndSendEmail(userData) {
try {
const user = await User.create(userData);
// Email Options
const mailOptions = {
from: 'your-email@gmail.com',
to: user.email,
subject: 'Welcome!',
text: `Hello ${user.name}, your record has been saved successfully!`
};
// Send Email
await transporter.sendMail(mailOptions);
console.log('Email Sent Successfully!');
} catch (error) {
console.error('Error:', error);
}
}
// Example Usage
saveUserAndSendEmail({ email: 'test@example.com', name: 'John Doe' });