Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send zip file using @sendgrid/mail

This is the code I have written to send email with attachment using @sendgrid

  const mailOptions = {}
  if(mailOptions){
    mailOptions.from = 'APP NAME'
    mailOptions.to = 'emailId'
    mailOptions.subject = 'Subject' // Subject line
    //mailOptions.attachments = attachments
    mailOptions.text = 'attachments'
  }
  const sendEmail = await sgMail.send(mailOptions)

But it only sends the mail with subject "no attachment"

The error I am getting when I uncomment the attachment line

{ Error: Bad Request
    at Request.http [as _callback] (node_modules/@sendgrid/client/src/classes/client.js:124:25)

Why this is happening can someone please help me.

like image 759
Profer Avatar asked Sep 10 '25 23:09

Profer


1 Answers

It's been a while since this question has been asked, but answering for future reference.

In order to fix the error, the attachment must have Base64 encoding - and its filetype should be set to 'application/zip'. The .js code to be input has also been vastly updated. An example today would look as follows

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

const fs = require("fs");

pathToAttachment = `${__dirname}/attachment.zip`;
attachment = fs.readFileSync(pathToAttachment).toString("base64");

const msg = {
  to: '[email protected]',
  from: '[email protected]',
  subject: 'Subject',
  text: 'Sent using Node.js',
  attachments: [{
    content: data.toString('base64'),
    filename: filename,
    type: fileType,
    disposition: 'attachment',
  }, ],
};
sgMail.send(msg).catch(err => {
  console.log(err);
});

Happy coding!

like image 93
Jinen Setpal Avatar answered Sep 12 '25 11:09

Jinen Setpal