Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

256
Vistas
How to get a response from nodemailer using netlify functions?

I am using netlify functions to send an email from the frontend and it works fine... as in it does send the email.

However on the clientside (browser) I can't get any response. I need a basic response that would allow me to do a if (status==="success") displayMessage() but I can't seem to get any response on the browser.

I get this message Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data However on sending the request via POSTMAN I get a response 'Email Sent Succesfully' which is the body part of the callback response.

Here's the function that I am using at .netlify/functions/sendMail

const nodemailer = require("nodemailer");

exports.handler = function (event, context, callback) {
  const mailConfig = {
    host: "smtp.mailgun.org",
    port: 465,
    secure: true,
    auth: {
      user: process.env.MAILGUN_USER,
      pass: process.env.MAILGUN_PASSWORD,
    },
  };
  const transporter = nodemailer.createTransport(mailConfig);

  transporter.verify((error, success) => {
    if (error) {
      console.log(error);
    } else {
      console.log("Ready to send emails");
    }
  });

  const messageData = JSON.parse(event.body);

  const { email, name, mobile, message, subject, recipient } = messageData;

  console.log(messageData);

  const mailOptions = {
    from: email,
    to: recipient,
    subject: subject,
    text: message,
  };

  transporter.sendMail(mailOptions, (error, success) => {
    if (error) {
      console.log(error);
      callback(error);
    } else {
      console.log("email sent");
      callback(null, {
        statusCode: 200,
        body: "Email sent successfully",
      });
    }
  });
};


and on the client side I have this

const form = document.querySelector("#message");

const submitMessage = (event) => {
  event.preventDefault();

  const formData = new FormData(form);

  formData.append("recipient", "testing@gmail.com");
  formData.append("subject", "Submission from website");

  const messageData = Object.fromEntries(formData);

  console.log(messageData);

  const url = ".netlify/functions/sendMail";
  const options = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(messageData),
  };

  fetch(url, options)
    .then((response) => response.json())
    .then((data) => console.log(data));
};

form.addEventListener("submit", submitMessage);

in the fetch request, I expected data to give me a response so I could trigger some action to display a success message..

Can someone advise me what I am doing wrong here?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I realised what I was doing wrong and here's the solution in case someone else faces the same issues.

In the callback from the netlify function I was sending the body as text

      callback(null, {
        statusCode: 200,
        body: "Email sent successfully",
      });

but in the clientside fetch request I was treating it as json

  fetch(url, options)
    .then((response) => response.json())
    .then((data) => console.log(data));

So basically I could either use a response.text() instead of response.json() for the fetch request or use JSON.stringify and return a JSON object from the callback. I preferred the JSON.stringify option as below for the callback

      callback(null, {
        statusCode: 200,
        body: JSON.stringify({
          status: "success",
          message: "Email sent successfully",
        }),
      });

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda