I keep encountering an issue with Nodemailer where it keeps throwing the error message "TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument needs to be a string or.."

The error message is incredibly long, but here is a brief excerpt:

    TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Object
    at PassThrough.Writable.write (_stream_writable.js:289:13)
    at PassThrough.Writable.end (_stream_writable.js:583:10)
    at Immediate._onImmediate (C:\Users\small\desktop\career-change\coding-round-2\portfolio-round1\recipe-app\projectv2\node_modules\nodemailer\lib
\mime-node\index.js:969:46)
    at processImmediate (internal/timers.js:456:21) {
  code: 'ERR_INVALID_ARG_TYPE'
}

This is my first experience with nodemailer or any email service. Initially, I used it with my personal gmail account, but encountered issues when gmail blocked it due to security concerns. To address this, I adjusted my email settings to allow access from less secure apps. Subsequently, this error started occurring.

To avoid potential Gmail-related issues, I also attempted using to generate a test email account automatically.

Below is the code snippet for nodemailer that I am using:

const express = require("express");
const router = express.Router();
const bodyParser = require("body-parser");
const nodemailer = require("nodemailer");

router.post("/contact", (req, res) => {
  const output = {
    msg: `You have a new contact request from ${req.body.name}`,
    userEmail: req.body.userEmail,
    subject: req.body.subject,
    message: req.body.message,
  };
  console.log(res);

  // create reusable transporter object using the default SMTP transport
  let transporter = nodemailer.createTransport({
    host: "smtp.ethereal.email",
    port: 587,
    auth: {
      user: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89e0ede8a7f9e6e5e5e0eae1bebac9ecfde1ecfbece8e5a7ece4e8e0e5">[email protected]</a>",
      pass: "JPtPvputy6n8JBzYe2",
    },
  });

  let mailOptions = {
    from: '"Nodemailer Contact" <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="14796d647166677b7a75787577775b65747b74777f74807c71c97c70786a73777374706276767135787e72">[email protected]</a>>', 
    to: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9ada0afafacbbaca7bdb9acbbbaaca6afb2afb8babfb6eda6bc988fa581ababa3e1acb0b2b4beb6b396bbb7b5">[email protected]</a>", 
    subject: "Node Contact Request", 
    text: output, 
    html: output, 
  };

  // send mail with defined transport object
  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      return console.log(error);
    } else {
      console.log(info);
    }
    res.send("email sent");
    console.log("Message sent: %s", info.messageId);

    console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
    
  });
});

module.exports = router;

Any insights on what this error implies? Feel free to ask for additional details if needed.

Answer №1

In my situation, I encountered an issue where I was trying to send data in the wrong format. To resolve this problem, I converted the property html to a string, which successfully resolved the issue. Since I was working with next.js, the compiler was interpreting my HTML as a JSX element.

       const mailOptions= {
            from: email,
            to: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0469656d68446369656d682a676b69">[email protected]</a>',
            subject: `FORMULARIO DE: ${req.body.name}`,
            text: req.body.message,
            html: `<div>${req.body.message}</div>`,
        }

Answer №2

It appears that the issue lies in the return statement. Instead of returning just the error, you should use JSON.stringify(error) and then retrieve the error from the sendMail function.

Answer №3

Encountering an error like this can be frustrating:

TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer. Received an instance of Object
  at validChunk (_stream_writable.js:281:10)
  at PassThrough.Writable.write (_stream_writable.js:316:21)
  at PassThrough.Writable.end (_stream_writable.js:585:10)
  at Immediate._onImmediate (/home/ajwebmaker/lsoftweb/node_modules/nodemailer/lib/mime-node/index.js:977:46)
  at processImmediate (internal/timers.js:461:21) {
    code: 'ESTREAM',
    command: 'API'
  }

To resolve this issue, try including the following lines in your code:

<div>Name:${req.body.message}</div>
<div>Email${req.body.message}</div>

Add these HTML snippets as many times as necessary to send emails successfully.

After making the changes, your code should look something like this:

const mailOptions= {
  from: email,
  to: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0568646c69456268646c692b666a68">[email protected]</a>',
  subject: `FORMULARIO DE: ${req.body.name}`,
  text: req.body.message,
  html: `<div>Name:${req.body.message}</div><div>Email${req.body.message}</div>`
}

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

export module from the express framework

function affirm(){ console.log("yes") } Element={} Element=affirm Element.something="something" Element.nothing="nothing" DEPICTED IN WEB BROWSER: In the code snippet above, if you were to console.log(Element), it would display ...

Mapping keys in a react component for efficient sorting

I'm facing some challenges when attempting to reorder keys from a state within my map function in React.. The original output is: monday : {1200: {…}, 1500: {…}, 1800: {…}, 2000: {…}, 2200: {…}, 0000: {…}, 0100: {…}, 0500: {…}, 0600: ...

The Express.js feature "app.use() mandates the use of middleware functions"

Currently, I am delving into learning Express.js 4 and Node, but I seem to have hit a roadblock with an error that has me stumped. I'm attempting to utilize the node-sass package to compile my sass code; however, I've encountered obstacles in ge ...

Exploring Jasmine and Karma for testing Angular 5 HTTP requests and responses

I am brand new to the concept of Test-Driven Development (TDD) and I am currently in the process of debugging a complex Angular 5 application for the company I work for. The application is functioning without any issues, but now I need to incorporate test ...

Potential memory leak detected in EventEmitter by Discord.js

One night while my bot was running on auto-pilot as I drifted off to sleep, a warning popped up out of the blue: MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 guildMembersChunk listeners added to [Client]. Use emitter.setMaxLi ...

Toggle draggable grid in jQuery

Imagine I have a grid set up using the following code: $( "#dragIt" ).draggable({ grid: [ 15, 15 ] }); Now, there is a checkbox located below the div. Is there a way for me to switch the grid on and off by toggling the checkbox? I've searched the of ...

Utilizing Facebook's UI share URL parameters within the Facebook app on mobile devices

Encountering an issue with the Fb ui share functionality on certain smartphones Here is the function: function shareFB(data){ FB.ui({ method: 'share', href: data, }, function(response){}); } Implemented as follows: $urlcod ...

Is it possible to vite package projects with node.js back-end?

Is it possible to package a back-end project using Vite, such as Express or Koa? What is the process for packaging a Node.js back-end project? ...

Mern, Issue with Removing Comments

Having trouble deleting comments within a single post? I keep encountering a 404 Error and I'm not sure why the post is not being found. I really need some assistance in figuring out what's causing this issue and why I'm unable to delete a c ...

Looking to adjust the background-image size of a table cell (td) upon clicking a specific

I have a website where I would like to display logos of different games with links attached to them. I have managed to adjust the size of the image on hover, but now I am looking for a way to keep the size bigger after clicking on the link. Is there a simp ...

I am having trouble successfully assigning the cookies that came in the response

Currently, I am facing an issue with my localhost React App running on port 3000 and an Express server on port 4000. Postman requests are setting the cookies correctly, and subsequent requests attach the cookie to the headers as expected. However, in React ...

The react component is not defined within the <Popup></Popup> tag

SOLVED: Big thanks to everyone who offered their assistance. Upon further investigation, I discovered that in the library I was using, the trigger={} functionality is specifically designed to work only with a button element. To address this issue, I took ...

What is the best way to ensure that a mapped type preserves its data types when accessing a variable?

I am currently working on preserving the types of an object that has string keys and values that can fall into two possible types. Consider this simple example: type Option1 = number type Option2 = string interface Options { readonly [key: string]: Op ...

All strings located between the specified phrases

I am attempting to extract strings that are located between two specific strings, but the output I am getting from using str.match is not what I anticipated: var text = "first second1 third\nfirst second2 third\nfirst second3 third"; var middles ...

Challenges with jQuery Form validation and submitting entries

I am having some issues with my form validation using jQuery. The current setup is working well, but I need to make a specific change that I am struggling with due to my limited knowledge of jQuery. I want to ensure that text boxes, such as first name an ...

Adjust image size using Node.js and ImageMagick

How can I resize images before sending them to users in Node.js using Express? im = require("imagemagick") app.get('/image/:dossier/:id/:taille', function (req, res) { var image = __dirname + '/public/img/bibliotheque/'+req.params ...

Place the div directly beside the input field on the right side

I am attempting to align a div directly beside the text being entered in a text input field. It seems logical to me that this could be achieved by measuring the length of the input value and positioning the div accordingly. However, the issue I am facing i ...

Solve the problem with SCSS at the component level in NextJS

I've decided to transition my regular React app to Next.js. In the past, I would simply import SCSS files using: import from '.componentName.scss' However, now I need to import them using: import style from 'componentName.module.scss ...

Having trouble iterating through an array of objects in Vue?

Having trouble looping through an array of objects in Vue3 <template> <div class="shadow-xl w-96 h-96 md:h-[600px] md:w-[600px] lg:my-12 lg:w-[700px] lg:h-[700px] rounded-md" > <button @click="getData">Get ...

Are there any public APIs available for testing JSONP AJAX calls?

Does anyone know of any public web API, aside from Twitter, that I can experiment with by making an ajax call using the jsonp protocol? ...