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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With