Question

: Automating Emails to Notify Users Two Days Before Free Trial Ends

  • 28 April 2024
  • 1 reply
  • 12 views

Badge +5

Hello,

I'm currently working on automating an email notification system where users who are on a free trial receive an email automatically 5 days after their initial sign-up. I'm using webhooks for this purpose. Below is the implementation snippet using Node.js, Express, and Nodemailer:

 

require("dotenv").config();
const express = require("express");
const bodyParser = require("body-parser");
const nodemailer = require("nodemailer");

const app = express();
const port = 3000;

app.use(bodyParser.json());

const transporter = nodemailer.createTransport({
  service: "gmail",
  auth: {
    user: process.env.EMAIL_USER,
    pass: process.env.EMAIL_PASS,
  },
});

async function sendMail({ to, from, subject, html }) {
  try {
    let info = await transporter.sendMail({
      from: from,
      to: to,
      subject: subject,
      html: html,
    });
    console.log("Message sent: %s", info.messageId);
    return "Email sent successfully";
  } catch (error) {
    console.error("Error sending email: %s", error);
    return "Failed to send email";
  }
}

app.post("/webhook", async (req, res) => {
  const authHeader = req.headers.authorization;
  const expectedAuthToken = process.env.AUTH_TOKEN;

  if (!authHeader || authHeader !== `Bearer ${expectedAuthToken}`) {
    return res.status(401).send("Unauthorized");
  }

  const data = req.body;

  if (
    data.event.type === "INITIAL_PURCHASE" &&
    data.event.data.period_type === "TRIAL"
  ) {
    const userId = data.event.data.app_user_id;
    const emailAddress = data.event.data.email;

    setTimeout(async () => {
      const message = await sendMail({
        from: process.env.EMAIL_USER,
        to: emailAddress,
        subject: "Reminder: Your Subscription Benefits",
        html: `<h1>Hello!</h1><p>Thank you for subscribing. Don't forget all the great features you can access!</p>`,
      });
      console.log(message);
    }, 432000000); // 5 days in milliseconds

    res.send("Webhook processed, email will be sent in 5 days.");
  } else {
    res.status(200).send("Webhook received, but no relevant action needed.");
  }
});

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});
 

Could you please review this setup and let me know if there are any potential issues with using webhooks in this manner or if there's a better approach to achieve the same functionality?

Thank you for your guidance!


This post has been closed for comments

1 reply

Userlevel 4
Badge +8

Hi, webhooks are the best way to achieve this kind of functionality. Your approach and code look good. If you end up having trouble with this working let me know and I’d be happy to assist further.