const nodemailer = require('nodemailer');
const logger = require('./logger');
// Create transporter
const createTransporter = () => {
return nodemailer.createTransporter({
host: process.env.EMAIL_HOST,
port: process.env.EMAIL_PORT,
secure: false, // true for 465, false for other ports
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS,
},
tls: {
rejectUnauthorized: false
}
});
};
// Email templates
const generateBookingConfirmationHTML = (context) => {
const { guest, booking, room } = context;
return `
Dear ${guest.firstName} ${guest.lastName},
Thank you for choosing The Old Vine Hotel! We're delighted to confirm your reservation.
Booking Details
Booking Number: ${booking.bookingNumber}
Confirmation Code: ${booking.confirmationCode}
Room: ${room.name} (${room.type})
Check-in: ${booking.checkInDate.toLocaleDateString()} (3:00 PM)
Check-out: ${booking.checkOutDate.toLocaleDateString()} (11:00 AM)
Guests: ${booking.numberOfGuests.adults} Adult(s)${booking.numberOfGuests.children ? `, ${booking.numberOfGuests.children} Child(ren)` : ''}
Nights: ${booking.numberOfNights}
Total Amount: $${booking.totalAmount.toFixed(2)}
${booking.specialRequests ? `
Special Requests
${booking.specialRequests}
` : ''}
What to Expect
- Luxury accommodations with premium amenities
- 24/7 concierge service
- Complimentary WiFi throughout the hotel
- Fine dining restaurant and bar
- Spa and fitness center access
Hotel Information
Address: 123 Luxury Avenue, Downtown District, City, State 12345
Phone: +1 (555) 123-4567
Email: info@oldvinehotel.com
If you need to modify or cancel your reservation, please contact us at least 24 hours in advance.
We look forward to welcoming you to The Old Vine Hotel!
Warm regards,
The Old Vine Hotel Team
`;
};
const generateBookingCancellationHTML = (context) => {
const { guest, booking, room, cancellationFee, refundAmount } = context;
return `
Dear ${guest.firstName} ${guest.lastName},
We have processed your cancellation request for the following booking:
Cancelled Booking Details
Booking Number: ${booking.bookingNumber}
Room: ${room.name}
Check-in Date: ${booking.checkInDate.toLocaleDateString()}
Check-out Date: ${booking.checkOutDate.toLocaleDateString()}
Original Amount: $${booking.totalAmount.toFixed(2)}
${cancellationFee > 0 ? `
Cancellation Fee: $${cancellationFee.toFixed(2)}
` : ''}
Refund Amount: $${refundAmount.toFixed(2)}
${refundAmount > 0 ? `
Your refund of $${refundAmount.toFixed(2)} will be processed within 5-7 business days and will appear on your original payment method.
` : ''}
We're sorry to see you cancel your stay with us. We hope to welcome you to The Old Vine Hotel in the future.
If you have any questions about this cancellation, please don't hesitate to contact us.
Best regards,
The Old Vine Hotel Team
`;
};
const generateContactFormHTML = (context) => {
const { name, email, phone, message } = context;
return `
Contact Details
Name: ${name}
Email: ${email}
Phone: ${phone || 'Not provided'}
Message
This message was sent from the hotel website contact form.
`;
};
// Main send email function
const sendEmail = async ({ to, subject, template, context, html, text }) => {
try {
const transporter = createTransporter();
let emailHTML = html;
// Generate HTML based on template
if (template && context) {
switch (template) {
case 'bookingConfirmation':
emailHTML = generateBookingConfirmationHTML(context);
break;
case 'bookingCancellation':
emailHTML = generateBookingCancellationHTML(context);
break;
case 'contactForm':
emailHTML = generateContactFormHTML(context);
break;
default:
throw new Error(`Unknown email template: ${template}`);
}
}
const mailOptions = {
from: `"The Old Vine Hotel" <${process.env.EMAIL_FROM}>`,
to,
subject,
html: emailHTML,
text: text || '', // Plain text version
};
const result = await transporter.sendMail(mailOptions);
logger.info(`Email sent successfully to ${to}`, {
messageId: result.messageId,
subject
});
return result;
} catch (error) {
logger.error('Email sending error:', {
error: error.message,
to,
subject,
template
});
throw new Error(`Failed to send email: ${error.message}`);
}
};
// Send bulk emails
const sendBulkEmails = async (emails) => {
const results = [];
for (const emailData of emails) {
try {
const result = await sendEmail(emailData);
results.push({ success: true, to: emailData.to, messageId: result.messageId });
} catch (error) {
results.push({ success: false, to: emailData.to, error: error.message });
}
}
return results;
};
// Send newsletter
const sendNewsletter = async (subscribers, subject, content) => {
const emails = subscribers.map(subscriber => ({
to: subscriber.email,
subject,
html: content,
template: null
}));
return sendBulkEmails(emails);
};
module.exports = {
sendEmail,
sendBulkEmails,
sendNewsletter
};