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

时间:2016-06-28 00:12:01

标签: node.js sendgrid multer

我正在尝试将文件附加到sendgrid而不将其存储到磁盘。我想用stream来处理它。

    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)

1 个答案:

答案 0 :(得分:3)

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

但您可以使用返回的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);
  /* ... */
});

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