Alvaro Vergara
Alvaro Vergara

Reputation: 83

Sending an array of attachments with node.js

I need to send an email using nodemailer with several attachments, but the number of those attachments must be defined by the size of an array. I know that nodemailer can send more than one attachment, but I have no idea how to send a variable number of attachments.

Here my code:

  const files = get(req, "body.data.files");

  files.forEach(file => {
   senderMail.send(file, {
    name: get(req, "body.data.files.name"),
    url: get(req, "body.data.files.url")
    });
  });


   let mailOptions = {
    from: "Me", // 
    sender address
    to: data.personal.user_email, // list of receivers
    subject:
       "An email with attachments"
    text: "someText",
    html: "",
    attachments: [
      {
        filename: name,
        path: url
      }
    ]
  };

Some data is obtained from a JSON.

Upvotes: 1

Views: 3914

Answers (1)

Jeffrey Roshan
Jeffrey Roshan

Reputation: 166

Prepare an array in the Nodemailer format and then attach it to the mail object.

const files = get(req, "body.data.files");

const attachments = files.map((file)=>{
  return { filename: file.name, path: file.url };
});


let mailOptions = {
  from: "Me", // 
  sender address
  to: data.personal.user_email, // list of receivers
  subject:
      "An email with attachments"
  text: "someText",
  html: "",
  attachments: attachments
};

Upvotes: 3

Related Questions