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

execute numerous Jssor Caption instances simultaneously

I have a Jssor slider and I want to create an animation for the first slide. My goal is to make two images come from the sides and merge in the center. I tried using a div for each image with a caption, and it works well. However, the second image starts ...

do not display entries with expired duration

update1: Unfortunately, even after testing in the sandbox, the result is still returning empty :( https://codesandbox.io/s/happy-https-u8lu2 After filtering my starsValues based on height and weight, I am able to get some results. However, I also n ...

Unable to locate module within a subdirectory in typescript

The issue I'm facing involves the module arrayGenerator.ts which is located in a subfolder. It works perfectly fine with other modules like Array.ts in the parent folder. However, when I introduced a new module called Sorting.ts, it started giving me ...

Trigger Vue method when the size of a div element changes

Is there a way to trigger a method every time the dimensions (width or height) of a div element change? <template> <div> </div> </template> <script> export default { methods: { updateSize() { // ...

Utilizing properties to transfer a reference object to a nested component

Is it safe to do the following in React: function Parent() { const myRef = useRef([1, 2, 3]); console.log("parent: " + myRef.current); return <Child myList={myRef.current} />; } function Child({ myList }) { const [currInt, setCurrInt] = useS ...

Data is present in a JavaScript array, yet it is returning a value of

In my quest to create an array of User IDs for an AJAX Post Request, I encountered a strange issue. Despite successfully retrieving and displaying the User IDs individually in console.log, once I push them to the connectionData array, accessing specific in ...

Choosing the Angular5 model

I'm currently working with an Angular5 project that has a <select> element bound to an array of customers. Here's the code snippet: <select class="form-control" [ngModel]="record.customer_id" (ngModelChange)="setCustomer($event)" name=" ...

When will the javascript file fire if it has this implementation?

Can someone help me make sense of this jquery snippet? (function( window, undefined ) { //All the JQuery code is included here ... })(window); I'm curious, if a .js file is loaded in a page using the <script> tag, at what point does it ...

The player remains unchanged

Hi, I am currently working on my app to update a player's age. To start off, I have added three players: const playerOne = store.dispatch(addPlayer({ firstName: 'Theo', lastName: 'Tziomakas', position: 'Goakeeper ...

Tips for employing e.preventDefault within the onChange event handler for a select element

Is there a way to prevent the select tag value from changing using preventDefault? I have successfully prevented input from changing the value with event.preventDefault, but have not been able to do the same for the select tag. Here is an example code sni ...

What methods can be used to ensure a required minimum delay time between function executions?

For my node function, I am aiming for a specific execution delay of around 5 seconds. The minimum delay needs to be implemented within the function itself, not externally, so external users are unaware of the delay. Therefore, I cannot rely on modules l ...

send multiple textbox values to controller in CodeIgniter

I am new to Codeigniter and I'm facing some difficulties in understanding how to accomplish a task. In my view page, there are five rows generated using a for loop. Each row consists of two select boxes and two input boxes. I don't know how to re ...

The provider of $modalInstance is currently unknown, leading to an error in the MainController

I'm currently facing an issue with my app's modals when trying to call them using $modalInstance. Despite following the advice from other similar questions I found, such as avoiding the use of ng-controller, my modal still isn't functioning ...

Unable to close Bootstrap 5 modal

All of my modal forms are functioning properly, except for one that I migrated from Bootstrap 4 to Bootstrap 5. This particular modal refuses to close. Neither the Close button (the X at the top of the popup) nor the Cancel button will close the modal. I ...

Enhance the security measures for a specific Swagger path

I currently have a Node.js API that I am working on integrating swagger documentation into. Clients are required to authenticate using JWT, which is why I have added the following security definition: securityDefinitions: UserSecurity: type: apiKey ...

Create a function to produce a list of dates within two specified date ranges using JavaScript

Looking for assistance as a beginner in JavaScript. Can anyone guide me on how to generate a list of dates between dateA and dateB? For instance: dateA = 07/01/2013 dateB = 07/01/2014 Desired outcome: 07/01/2013, 07/02/2013, 07/03/2013, 07/04/2013...a ...

Guide on duplicating text and line breaks in JavaScript

There is some text that looks like this text = 'line 1' + "\r\n"; text+= 'line 2' + "\r\n"; text+= 'line 3' + "\r\n"; I have developed a function to help facilitate copying it to the clipboard ...

Having trouble getting NodeJS Express with SSL to function properly when using an Nginx reverse proxy

Encountering an unexpected issue while setting up a NodeJS app on Ubuntu 16.04. The app seems to function only with the http dependency and not the https dependency. The NodeJS app is running on port 8081, and I've implemented a Nginx reverse proxy w ...

What is the best way to send an array of strings through an AJAX call?

Utilizing ajax to send an array of strings to another page has been a bit tricky for me. Here is the array located on nomes.php [ 'Home','A empresa','funcionarios','Quem Somos?','Historia','Inicio&ap ...

Creating Beautiful Tabs with React Material-UI's Styling Features

I've been delving into React for a few hours now, but I'm struggling to achieve the desired outcome. My goal is to make the underline color of the Tabs white: https://i.stack.imgur.com/7m5nq.jpg And also eliminate the onClick ripple effect: ht ...