Building a service which sends emails everyday to the user at a particular time. (NOT RUNNING)

20 Views Asked by At

i was writing code for a service which sends email daily to the user at the given time input by the user in the frontend. The time gets stored in timings collection for that particular user and then, a cron job is scheduled at that time. Right now, the cron job is scheduling and sending email at that time for the present day, but its not doing this daily. Please help me with this issue and any suggestions that what can be the problem or any things to keep in mind to make this run? I have attached the controller file which handles the email scheduling and sending api.

const cron = require('node-cron');
const nodemailer = require('nodemailer');
const googleNewsScraper = require('google-news-scraper');
const NotifyTiming = require('../models/timingModel.js');

const fetchNotifyTimings = async (req, res) => {
    try {
        const userId = req.user._id;
        const notifyTimings = await NotifyTiming.find({ addedBy: userId }).lean();
        res.json(notifyTimings);
    } catch (error) {
        console.error('Error fetching notify timings:', error);
        res.status(500).json({ error: 'Failed to fetch notify timings' });
    };
};


const scheduleEmail = async (req, res) => {
    const { time } = req.body;
    try {
        let notifyTiming = await NotifyTiming.findOne({ addedBy: req.user._id });
        if (!notifyTiming) {
            notifyTiming = new NotifyTiming({
                time: `${time.hour}:${time.minute}`,
                addedBy: req.user._id
            });
        } else {
            notifyTiming.time = `${time.hour}:${time.minute}`;
        }
        await notifyTiming.save();

        const cronSchedule = `0 ${time.minute} ${time.hour} * * *`;
        console.log(`Scheduling cron job for: ${cronSchedule}`);
        notifyTiming.cronJob = cron.schedule(cronSchedule, async () => {
            try {
                console.log('Scraping news articles...');
                const articles = await googleNewsScraper({ searchTerm: 'AI' });
                const formattedData = formatData(articles);
                await sendEmail(formattedData);
                console.log('Email sent successfully');
            } catch (error) {
                console.error('Error scraping news and sending email:', error);
            }
        }, { timezone: 'Asia/Kolkata' });

        console.log('Cron job scheduled successfully');
        res.send('Email scheduled successfully');
    } catch (error) {
        console.error('Error scheduling email:', error);
        res.status(500).send('Failed to schedule email. Please try again');
    };
};


const formatData = (articles) => {
    const allowedKeywords = ['Healthcare', 'AI']; // Add your desired keywords here
    return articles.filter(article => {
        const title = article.title.toLowerCase();
        return allowedKeywords.some(keyword => title.includes(keyword.toLowerCase()));
    }).map(article => {
        return {
            title: article.title,
            subtitle: '',
            link: article.link,
            image: '',
            source: article.source,
            time: article.time,
            content: '',
            favicon: '',
        };
    });
};

const sendEmail = async (data) => {
    const transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: `${process.env.MY_EMAIL}`,
            pass: `${process.env.MY_PASSWORD}`
        }
    });

    const emailContent = {
        from: `${process.env.MY_EMAIL}`,
        to: `${process.env.RECIPIENT_EMAIL}`,
        subject: 'Testing',
        html: generateHTML(data)
    };

    await transporter.sendMail(emailContent);
};

const generateHTML = (data) => {
    let html = '<ul>';
    data.forEach(article => {
        html += `
      <li>
        <strong>${article.title}</strong><br>
        <a href="${article.link}">${article.source}</a><br>
        <small>${article.time}</small><br>
      </li>
    `;
    });
    html += '</ul>';
    return html;
};

module.exports = {
    scheduleEmail,
    fetchNotifyTimings
};

Please help me with this

I tried with node-schedule library also, but I wasn't getting the email at that time the next day.

0

There are 0 best solutions below