How to Send Email Using Cron Job in Node.js
Tags: node, javascript, webdev, programming
Published: 2024-05-22 14:05:21


Automating email sending is a common requirement in many applications, whether for sending newsletters, reminders, or notifications. Using cron jobs in Node.js can simplify this task significantly. In this post, we'll walk through setting up an email automation system using the Pulse library, which leverages MongoDB for task management.

## Setting Up Your Environment

First, ensure you have Node.js and MongoDB installed on your system. Then, create a new Node.js project and install the necessary packages:

```bash
npm init -y
npm install express @pulsecron/pulse nodemailer --save
```

## Integrate Pulse with Express
Here’s a step-by-step guide to integrating Pulse with an Express application for email scheduling:

### 1.Import Dependencies and Setup Express
Begin by importing required modules and setting up the Express server:

```typescript
import express from 'express';
import Pulse from 'pulse';
import nodemailer from 'nodemailer';

const app = express();
const port = 3000;
app.use(express.json());
```


### 2.Configure Pulse
Set up Pulse to connect to MongoDB, where jobs will be managed:

```typescript
const mongoConnectionString = 'mongodb://localhost:27017/pulse';
const pulse = new Pulse({
  db: { address: mongoConnectionString, collection: 'cronjob' },
  defaultConcurrency: 4,
  maxConcurrency: 4,
  processEvery: '10 seconds',
  resumeOnRestart: true
});
```


### 3.Configure Nodemailer
Set up Nodemailer for sending emails:

```typescript
const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'your-email@gmail.com',
    pass: 'your-email-password'
  }
});
```

### 4.Define Email Job
Create a job definition for sending emails:
    
```typescript
pulse.define('send email', async (job, done) => {
  const { to, subject, text } = job.attrs.data;
  const mailOptions = {
    from: 'your-email@gmail.com',
    to,
    subject,
    text
  };

  try {
    await transporter.sendMail(mailOptions);
    console.log(`Email sent to ${to}`);
    done();
  } catch (error) {
    console.error(`Failed to send email to ${to}`, error);
    done(error);
  }
}, { shouldSaveResult: true });

```


### 5.Express Route to Trigger Email Job
Implement a route to schedule emails:
    
```typescript
app.post('/send-email', async (req, res) => {
  try {
    await pulse.start();
    const { to, subject, text, scheduleTime } = req.body;
    const job = pulse.create('send email', { to, subject, text });
    await job.schedule(new Date(scheduleTime)).save();
    res.status(200).send('Email scheduled successfully');
  } catch (error) {
    console.error(error);
    res.status(500).send('Failed to schedule email');
  }
});
```


### 6.Event Listeners
Add listeners for various job events:
```typescript
pulse.on('success', (job) => {
  console.log(`Job <${job.attrs.name}> succeeded`);
});

pulse.on('fail', (error, job) => {
  console.log(`Job <${job.attrs.name}> failed:`, error);
});
```

### 7.Start the Server
Launch your Express server:

```typescript
app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});
```

## Conclusion
Implementing and managing such a system yourself is necessary but can be tedious and time-consuming. To focus more on product engineering, consider using a cloud service like [Pulsecron](https://pulsecron.com) for your scheduling needs. Pulsecron offers a managed solution that simplifies the entire process, allowing you to concentrate on building great features for your users.

👉 [For the complete code and further details, please refer to the GitHub repository](https://github.com/pulsecron/pulse/blob/main/examples/send-eamil.example.ts)

👉 [Learn more about Pulsecron's event-based scheduling solutions](https://www.pulsecron.com/)

👉 [Join our open source project related to this topic](https://github.com/pulsecron/pulse)