Nodemailer functions flawlessly when used locally, but experiences issues when deployed live

function sendEmail(num, email, customerName) {
    var readHTMLFile = function (path, callback) {
        fs.readFile(path, { encoding: 'utf-8' }, function (err, html) {
            if (err) {
                throw err;
                callback(err);
            }
            else {
                callback(null, html);
            }
            
        });
    };

let transporter = nodemailer.createTransport({
        host: "smtp.gmail.com",
        secure: true,
        port: 465,

        auth: {
            user:process.env.USEREMAIL,
            pass:process.env.USERPASS
        },
    });
 
    readHTMLFile(__dirname + '/views/layouts/first.html', function (err, html) {
        var template = handlebars.compile(html);
        var replacements = {
            otp: `${num}`,
            customerName: `${customerName}`

        };
        var htmlToSend = template(replacements);
        var mailOptions = {
            from: process.env.USEREMAIL,
            to: email,
            subject: "Hello ✔",
            html: htmlToSend
        };
        transporter.sendMail(mailOptions, function (error, response) {
            if (error) {
                console.log(error);
            } else {
                console.log("Email sent");
            }
        });
    });
}

Everything was functioning correctly on my localhost:8000. However, after uploading and hosting it with my cyclic.sh account, the application seems to be working fine and I receive a success message, but unfortunately, no emails are being received in my inbox. The sendEmail function is not behaving as expected in the live environment, although it works perfectly locally. What could be causing the issues with the sendEmail function?

Answer №1

I encountered a similar issue and resolved it by incorporating sendmail into a promise

new Promise((resolve, reject) => {
      transporter.sendMail(mailOptions, function (error, response) {
            if (error) {
                reject(error)
            } else {
                resolve("email sent")
            }
        });
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the steps for setting up node.js, couchdb, and other tools on Amazon EC2?

Embarking on the journey of server administration for the first time is both daunting and exciting! As a node.js developer, I have relied on Nodejitsu until now. However, with rising prices, I am now exploring setting up my own server using AWS. My develo ...

Integration of GoogleMaps API v3, creating markers using Node.JS and Javascript, utilizing require() function for module exports

I am currently working on a node.js application that displays markers on Google Maps based on locations stored in the database. These locations are then converted and saved to a .txt file. Everything works smoothly up to this point. When I use console.log( ...

The EmberJS Express API encountered an error: TypeError - the app.route function is not recognized within module.exports

I've hit a roadblock with a server API in my Ember project for the past week. I'm struggling to make a modular API function properly and it's becoming quite frustrating. Console related: mongod, node server, heroku local (or ember s) The ...

"An unanticipated stream issue occurred within the pipeline" by Node.js

My application consists of Node.js, Express, and various middleware such as connect-assets and express.static. Everything is currently running on my local machine (OSX, using Node 0.8) in development mode (hence the use of express.static). An important d ...

npm fails with the error message 'ERR! callback() was not invoked'

While attempting to set up vue-cli on my system, I encountered an issue with the installation process. npm install -g @vue/cli The error message I received was: Unhandled rejection Error: EACCES: permission denied, mkdir '/home/moeketsi/.npm/_cac ...

An issue occurred while recognizing the create-react-app, despite being duly installed

After successfully installing create-react-app, I encountered an issue when attempting to create my own app. A message stating 'create-react-app' is not recognized as an internal or external command appeared. You can see the exact error message ...

EJS file not displaying stylesheets and images correctly during rendering

I'm currently in the process of building a website, but when I try to render an ejs file (index.ejs), only the HTML portion is displayed without showing any stylesheets, fonts, or images. Here is the code snippet for linking the stylesheets: <!D ...

"Using nginx to proxy a Node.js Express application running on a remote server within a sub

I am facing a challenge where I need to host multiple node applications on a single server. To achieve this, I have set up the applications to run on different ports and can access them by specifying the IP address along with the respective port numbers. ...

The serverless-plugin-split-stacks plugin does not reduce the overall resources in the root configuration when deployed serverlessly

After implementing the configuration changes for the serverless-plugin-split-stacks plugin, I noticed that the number of resources in the main stack remains unchanged. This poses a problem because CloudFormation has a maximum limit of 500 resources, and I ...

The issue arises when using multiple route files in Route.js, as it hinders the ability to incorporate additional functions within the

After breaking down Route.js into multiple controllers, I'm stuck on why I can't add an extra function to block permissions for viewing the page. // route.js module.exports = function(app, passport) { app.use('/profile&apos ...

unable to send an array from an AngularJS service to a web API

There seems to be an issue with passing the value of brandSelection in the web API controller. Here is my Angular service's $http.get() method: var _getItemByCategoryId = function (categoryId, currentPageNum, brandSelection) { var deferred = $q ...

Print the message in the Google Cloud Logging console when a request is made

Using NodeJS with Express in my application deployed to Google Cloud Run, I have encountered an issue with the logs. The request log from Google and the console.logs I intentionally emit can become mixed up when handling a large number of requests. I disc ...

Do you think it's feasible to configure cookies for express-session to never expire?

Is there a way to make cookies never expire for express-session? If not, what is the maximum maxAge allowed? I came across some outdated information on setting cookie expiration on SO (over 10 years old) and here on express, which mentions a maxAge of 1 y ...

What is the alternative method to adjust the npm prefix without using configuration?

After mistakenly setting the npm prefix to a non-existent location, I'm wondering if there's a configuration file that can be modified to revert this change. Currently, my options seem limited to: Fully uninstalling Node (npm not responding af ...

Error encountered: Mongoose server selection error - connection refused on ::1:27017

import express from 'express' const app = express(); const port = process.env.PORT || 8000; import mongoose from 'mongoose'; mongoose.connect("mongodb://localhost:27017/schooldb").then(() => { console.log("connec ...

Encountering a Route Not Found Error on Heroku with Node and Express Deployment

Once I deployed my app to Heroku, it started having trouble finding the API path that was set up in Express. The code runs perfectly fine on my local machine, but on Heroku, I keep getting a 404 - Page Not Found error. This is how the router is set up: c ...

What could be causing my node server's REST endpoints to not function properly?

Here is a snippet of my index.js file: var http = require('http'); var express = require('express'); var path = require('path'); var bodyParser = require('body-parser') var app = express(); var currentVideo = &apos ...

Warning: Attempting to destructure the property 'name' from 'req.body', which is undefined, is causing a TypeError

Currently, I am diving into the world of MERN Stack web development and running into a unique issue. When using Postmate to input data from the body to the database, everything works smoothly when done from the server.js file. However, when attempting the ...

How to Avoid Duplicating Documents in MongoDB?

I'm currently exploring effective methods to avoid saving duplicate documents in MongoDB. Currently, my form captures the user's URL input. The workflow is as follows: Validate if the user's URL is valid (using dns.lookup). If the use ...

Can someone guide me on the process of adding a personalized emoji to my discord bot?

After creating my own discord bot, I'm ready to take the next step and add custom emojis. While tutorials have helped me understand how to use client.cache to type an emoji, I'm unsure of how to upload them and obtain their ID for use in my bot. ...