user10874312
user10874312

Reputation:

nodemailer attachment create excel file error in nestjs

I am trying to send an email after creating an excel file.

I use nestjs and typeorm, my code is below.


import * as XLSX from 'xlsx';

let file: Map<string, any> = new Map();
      for (const t in UserType) {
        const data = await this.myDataRepository.find({
          select: ['userId', 'userName'],
          where: {userType : t},
          order: {
            userId: 'DESC',
          },
        });
        //createExcelFile
        var wb = XLSX.utils.book_new();
        var ws = XLSX.utils.json_to_sheet<UserGameCount>(data);
        XLSX.utils.book_append_sheet(wb, ws, 'TestWB.xlsx');

        var wbout = XLSX.write(wb, {
          type: 'base64',
          bookType: 'xlsx',
          bookSST: false,
        });

        file.set(t, wbout);
      }

      const result = await this.commonService.testsendMail(
        'myEmail@gmail',
        file,
      );
async testsendMail(email: string, file: Map<string, any>) {
    try {
      const att: {
        filename: string;
        contents: any;
        contentTransferEncoding: string;
        contentType: string;
      }[] = [];
      file.forEach((value: any, key: string) => {
        att.push({
          filename: key + '.xlsx',
          contents: Buffer.from(value).toString('base64'),
          contentTransferEncoding: 'base64',
          contentType:
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });
      });
      const mailOptions = {
        from: 'your mail',
        to: email,
        subject: 'subject',
        html: 'content',
        attachments: att,
      };

      await transporter.sendMail(mailOptions);

      
    } catch (error) {
      console.log(error);
      
    }
  }

Emails are sent normally. Attachments are also sent normally according to the number of userTypes.

But the size of the file is 0kb and the file does not open.

Even if I change the data to json format, Even if I change the XLSX.write option to buffer instead of base64, the same error occurs. How can I solve this?

Upvotes: 0

Views: 391

Answers (1)

user10874312
user10874312

Reputation:

I solved the part of generating excel using excel4node instead of xlsx.

var wb = new XLSX.Workbook();
var ws = wb.addWorksheet(t);

for (let i = 0; i < data.length; i++) {
          ws.cell(i + 1, 1).number(data[i].userId);
          ws.cell(i + 1, 2).string(data[i].name);
        }

const filename: string = new Date().getMonth() + '.xlsx';
      const f = await wb.writeToBuffer();

Upvotes: 0

Related Questions