Nodemailer does not seem to work with netlify, it works on localhost

Hello,

I have a functioning website that everything works as intended but I am having issues with one aspect that I don’t know how to solve.

The issue is that when I call the post API and the code runs through. It does not seem to send the emails required through node mailer, res.send seems to work. Here is the code:

const express = require("express");
const nodemailer = require("nodemailer");
const app = express();
const router = express.Router();
const serverless = require("serverless-http");

let transporter = nodemailer.createTransport({
    host: "hidden for netlifty post",
    port: 465,
    secure: true, // true for 465, false for other ports
    auth: {
      user: 'hidden for netlifty post', 
      pass: 'hidden for netlifty post', 
    },
  });

router.post('/email', (req,res) =>{

    const data = req.body;
    
    const info = {
        from: '"Socialway Marketing" <customer-relations@socialway.ca>', // sender address
        to: data.emailsending, // list of receivers
        subject: "Socialway Marketing", // Subject line
        text: "HOLD UP! Have you ever considered levelling up your business to the next step? The average business owner spends around 10 hours a week working on marketing their business. We can cut that 10 hours, and thrice the amount of customers you recieve. We are experts in every aspect of marketing, we have gotten proven results. Go to socialway.ca to check us out.", // plain text body
        html: { path: './apps/emailtemp.html' }, // html body
      };

      transporter.sendMail(info, function(err, info) {
        if (err) {
          console.log(err)
        } else {
          console.log(info);
        }
     });

    res.send("Marketing Email Has Been Shipped, Return to Sending Page");

    res.end();

})

app.use(`/.netlify/functions/api`, router);

module.exports = app;
module.exports.handler = serverless(app);

For the HTML code and more details, please ask and I’ll send

Hi @itsuki

I can’t tell from the code if it is something to do with Express (which I seldom use) or with Nodemailer. I can however share a previously working function that used Nodemailer.

Hello, I have implemented your code, and when I ran it through netlify, it spat out internal server error.

I might have architected/structured my code badly because I wrote the code and then added the netlify expressjs last minute to make it work. But I may have to restructure everything in order to use proper netlify functions. If anybody can link me a tutorial, that would be helpful.

const express = require("express");
const nodemailer = require("nodemailer");
const app = express();
const router = express.Router();
const serverless = require("serverless-http");

router.post('/email', (req,res) =>{

    const data = req.body;
    
    if (event.httpMethod !== "POST") {
      return {
        statusCode: 405,
        headers: { Allow: "POST" },
        body: "Method not allowed"
      };
    }
  
    // Passed all checks...
    try {
      // Form elements
  
      // See https://nodemailer.com/ for more
      const transporter = nodemailer.createTransport({
  
        // Follow the instructions from your mail provider.
        host: "mail.privateemail.com",
        port: 465,
        secure: true,
        auth: {
            user: 'hidden for netlify',
            pass: 'hidden for netlify'
        }
  
      });
    
      const msg = {
  
        // These settings will work with Ethereal Email
        // Where messages should get delivered
        to: data.emailsending,
        // Who they are coming from (the submitter)
        from: `"Socialway Marketing" <customer-relations@socialway.ca>`,
  
        // Depending on the service (e.g. Zoho), you my need may need send 
        // to/from yourself. Remember to set replyTo so you know who it came from
        // to: `"${process.env.MAIL_NAME}" <${process.env.MAIL_EMAIL}>`,
        // from: `"${process.env.MAIL_NAME}" <${process.env.MAIL_EMAIL}>`,
  
        // Set submitter as reply-to
        // replyTo: `"${yourname}" <${email_address}>`,
        // Could also CC the submitter so they have a copy too
        // cc: `"${yourname}" <${email_address}>`,
  
        // Set a meaningful subject
        subject: `Message from ${process.env.SITE_TITLE} contact form`,
  
        // Add the message and short_url
        text: "HOLD UP! Have you ever considered levelling up your business to the next step? The average business owner spends around 10 hours a week working on marketing their business. We can cut that 10 hours, and thrice the amount of customers you recieve. We are experts in every aspect of marketing, we have gotten proven results. Go to socialway.ca to check us out.", // plain text body
        
        // Want HTML?
        html: { path: './apps/emailtemp.html' }, // html body
      };
  
      // Send
      let info = transporter.sendMail(msg);
  
      // Check response
      if (info.messageId){
  
        // All good
        return {
          statusCode: 200,
          body: JSON.stringify({
            msg: "Your message was sent. Thank you."
          })
        };
  
      }
  
    }
    catch(err) {
      
      // Log error
      console.log(err)
      // Return message
      return {
        statusCode: 500,
        body: JSON.stringify({
          msg: "Could not send your message. Please try again."
        })
      };
    }

    res.send("Marketing Email Has Been Shipped, Return to Sending Page");

    res.end();

})

app.use(`/.netlify/functions/api`, router);

module.exports = app;
module.exports.handler = serverless(app);

Okay, I have been doing everything wrong. I have extended my research and I can not node mail regularly because its a HTTP server function. I have to learn HTTPS Serverless functions with Netlify in order to make it work through an API call. Hopefully it will work after I restructure everything.

1 Like

Thanks for coming back and sharing this!