node.js - 如何使用 Sendgrid 和 Multer 将文件附加到电子邮件

标签 node.js sendgrid multer

我正在尝试将文件附加到 sendgrid,而不将它们存储到磁盘。我想使用流来处理这个问题。

    var multer  = require('multer');
    var upload = multer({ storage: multer.memoryStorage({})});
    mail = new helper.Mail(from_email, subject, to_email, content);
    console.log(req.body.File);
    attachment = new helper.Attachment(req.body.File);
    mail.addAttachment(attachment)

最佳答案

我认为使用流是不可能的,因为:

但是您可以使用返回的 buffer 来实现它作为附件,例如:

var multer  = require('multer')
  , upload = multer({ storage: multer.memoryStorage({})})
  , helper = require('sendgrid').mail;

app.post('/send', upload.single('attachment'), function (req, res, next) {
  // req.file is the `attachment` file
  // req.body will hold the text fields, if there were any

  var mail = new helper.Mail(from_email, subject, to_email, content)
    , attachment = new helper.Attachment()
    , fileInfo = req.file;

  attachment.setFilename(fileInfo.originalname);
  attachment.setType(fileInfo.mimetype);
  attachment.setContent(fileInfo.buffer.toString('base64'));
  attachment.setDisposition('attachment');

  mail.addAttachment(attachment);
  /* ... */
});

如果与大附件或高并发一起使用,可能会影响内存使用(内存不足错误)。

关于node.js - 如何使用 Sendgrid 和 Multer 将文件附加到电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38065118/

相关文章:

node.js - 如何更新 node.js 并在 Travis CI 的 python 项目中安装 grunt/bower?

django - Heroku 临时存储、Sendgrid 和附件

css - 为什么 CSS 在发送 HTML 电子邮件时不起作用?

javascript - 如何使用 excel.js 库编辑 Multer 发布的文件?

node.js - 在同一 POST 请求上使用 multer (NodeJS) + 其他表单数据上传文件 (Angular)

ios - 为什么ios上传文件时没有调用nodejs multer上的onParseEnd回调?

node.js - Windows 版 Node.js 和 Mac OS 版 Node.js 之间的主要区别?

javascript - GroupBy CSV 文件中的数组元素并有助于减少代码

javascript - Node js 从模块化代码结构缩小并连接到单个文件

javascript - 部署到 Vercel 时,Sendgrid 电子邮件不会发送