Categories
Javascript Learning Tech

What to do when you get Error: sgmail send error Bad Request (400) The attachment content must be base64 encoded. attachments.0.content for nodejs or in next js application?

Okay well, this error occurred when you try to send the generated buffer data as an attachment using @sendgrid/mail service.

To tackle issue, will simply paste the previous line of code and the fix line of code so data was then send as base64 content as required with the @sendgrid/mail service

  res.send(response); //previous line of response from nextjs api

after adding the fix over same above line using Buffer

  res.send(Buffer.from(response).toString('base64')); // to base64 string as an output resolve the above issue

If anyone wants to look for the entire piece of file code, here you go:

// import the necessary node libraries
const chromium = require('chrome-aws-lambda');
const puppeteer = require('puppeteer');
import { createEmailTemplate } from "../../api/functions/index";
// var Buffer = require('buffer/').Buffer  // note: the trailing slash is important!

export default async (req, res) => {

    // console.log({ m: req.method.toLowerCase(), body: Object.keys(req.body).length });

    if (req.method.toLowerCase() !== 'post' ||
        (!Object.keys(req.body).length ||
            process.env.YOUR_EXTERNAL_API_SECRET !== req.body.your_api_secret)) {
        res.status(403).send("Access denied");
        return;
    }

    const { generateType, store } = req.body; // && JSON.parse(JSON.streq.body);
    const templatePayload = {
        ...req.body,
        assetsBaseURL: process.env.NEXT_PUBLIC_ASSETS_BASE_URL,
        siteName: process.env.SITE_NAME,
        logoPath: store?.logo,
    };
    // console.log({ templatePayload });
    try {

        // compile the file with handlebars and inject the customerName variable
        const html = createEmailTemplate("my-invoice", templatePayload);

        // simulate a chrome browser with puppeteer and navigate to a new page
        const browser = await puppeteer.launch({
            args: chromium.args,
            // defaultViewport: chromium.defaultViewport,
            // defaultViewport: generateType && generateType === 'pdf' ? chromium.defaultViewport : { width: 640, height: 1200 }, //chromium.defaultViewport,
            executablePath: await chromium.executablePath,
            headless: generateType && generateType === 'pdf' ? true : chromium.headless,
            ignoreHTTPSErrors: true,
        });

        const page = await browser.newPage();
        await page.setViewport({
            width: 640,
            height: page.viewport().height, // + 400,
            deviceScaleFactor: 1,
        });

        // set our compiled html template as the pages content
        // then waitUntil the network is idle to make sure the content has been loaded
        await page.setContent(html, { waitUntil: 'networkidle0' });

        // convert the page to pdf with the .pdf() method
        let response;
        if (generateType && generateType === 'pdf') {
            const pdf = await page.pdf({ format: 'A4' });
            response = pdf;
        } else {
            const screenshot = await page.screenshot({ fullPage: true });
            response = screenshot;
        }
        await browser.close();

        // // send the result to the client
        res.statusCode = 200;
        res.send(Buffer.from(response).toString('base64'));

        // CODE BELOW WRITE RESPONSE AS HTML AND IMAGE IS DISPLAYED, TESTTED 
        // res.writeHead(200, { 'Content-Type': 'text/html' });
        // res.write('<html><body><img src="data:image/jpeg;base64,')
        // res.write(Buffer.from(response).toString('base64'));
        // res.end('"/></body></html>');

    } catch (err) {
        console.log(err);
        res.status(500).json({ message: err.message });
    }
};

I hope this find useful to anyone who facing this question or challenge.

Happy learning! Enjoy!