【问题标题】:Sending an email with an Excel file as an attachment (nodemailer)发送带有 Excel 文件作为附件的电子邮件 (nodemailer)
【发布时间】:2021-07-30 16:08:07
【问题描述】:

我正在尝试使用 nodemailer 库向用户发送电子邮件。但是,我还需要发送一个 Excel 文件 (.xlsx) 作为附件。我在发送 .csv 文件方面取得了一些成功,但我需要将其作为 .xlsx 发送。 到目前为止,这是我的代码

import xlsx from 'xlsx';
import nodemailer from 'nodemailer';
import os from 'os';
import path from 'path';
import fs from 'fs-extra';

const mail = 'testmail@something.com';

const transporter = nodemailer.createTransport({...});

const wb = xlsx.utils.book_new();
wb.Props = { Title: 'Excel', Subject: 'Excel' };
wb.SheetNames.push('Excel');
const wData = [['Some','Data']];
const ws = xlsx.utils.aoa_to_sheet(wData);
wb.Sheets['Excel'] = ws;
const wbout = xlsx.write(wb, { bookType: 'xlsx', type: 'binary' });

const fileName = '${mail}_${Date.now()}.xlsx';
const tempFile = path.join(os.tmpdir(), fileName);
await fs.writeFile(tempFile, wbout);

const mailOptions = {
  from: 'johndoe@test.com',
  to: mail,
  subject: 'Excel',
  attachments: {
    filename,
    content: wbout,
    path: tempFile
  }
};

return transporter.sendMail(mailOptions);

到目前为止,我无法按预期发送,所以你们能帮帮我吗? 另外,我试过看: This post

但是,他们的解决方案似乎基于将文件作为 .csv 发送,这是我不想要的。

【问题讨论】:

    标签: javascript node.js react-native nodemailer


    【解决方案1】:

    我也有同样的困难,在我的情况下,将contentType 设置为“application/octet-stream”:

    const mailOptions = {
        from: this.sender,
        to: this.recipient,
        subject: "report",
        text: "report",
        attachments: [
            {
                filename: 'report' + '.xlsx',
                content: Buffer.from(buffer),
                contentType: 'application/octet-stream',
            }
        ],
        headers: {'x-myheader': 'test header'}
    };
    

    【讨论】:

      猜你喜欢
      • 2021-11-24
      • 2019-09-25
      • 2012-10-05
      • 2018-05-12
      • 1970-01-01
      • 1970-01-01
      • 2012-06-15
      • 2015-09-09
      相关资源
      最近更新 更多