rosh
rosh

Reputation: 97

how to send email with .xlsx attachment in sendgrid?

Below is the message object used to send emails.

 message = {
        to: toEmail,
        from: emailInfo.emailFromAddress,
        subject: emailInfo.emailSubjectTemplate,
        attachments: [
          {
            filename: fileName,
            content: base64str,
            contentId: fileName,
            disposition: "attachment"
          }
        ],
        html: emailMessageBodyTemplate
      };

The content is encoded into a base64 string by the following below code.

const base64_encode = file => {
  var bitmap = fs.readFileSync(file);
  return new Buffer(bitmap).toString("base64");
};

I don't know where I m going wrong but I'm getting the error as follows.

message:"The content value must be a string at least one character in length."

but the content is not empty when I debug it is a base64 string.

Please help.

Upvotes: 1

Views: 9093

Answers (3)

Craig
Craig

Reputation: 19

I'm also using XLSX but found using base64 format caused issues with the file extension.

Error message in excel

I found setting the output data encoding to buffer solved the issue for me.

const content = write(workbook, { type: 'buffer', compression: true });

Upvotes: 0

Krunal Limbad
Krunal Limbad

Reputation: 1573

On this page it describes exactly your error.

I believe in this error content means your message or a text as error describes

You may not send an email with no content.

And as per the API docs,you are missing a required parameter content.

message = {
            to: toEmail,
            from: emailInfo.emailFromAddress,
            subject: emailInfo.emailSubjectTemplate,
            content:[
              {
                 type : 'string',
                 value : 'message'
              }
            ],
            attachments: [
              {
                filename: fileName,
                content: base64str,
                contentId: fileName,
                disposition: "attachment"
              }
            ],
            html: emailMessageBodyTemplate
          };

Hope this helps.

Upvotes: 3

Barak Hofi
Barak Hofi

Reputation: 31

I've encountered the same issue and in my case I used 'xlsx' npm lib, to implement the solution as follow:

const workbook = XLSX.utils.book_new();
const ws = XLSX.utils.aoa_to_sheet(data);
XLSX.utils.book_append_sheet(workbook, ws, 'Accounts');

// write the file in base64 format
const report = XLSX.write(workbook, { type: 'base64', compression: true });

const attachment = {
    content: report,
    filename: `MyReport.xlsx`,
    type: 'text/html',
    disposition: 'attachment'
};

Upvotes: 3

Related Questions