【问题标题】:How to attach files to email using Sendgrid and Multer如何使用 Sendgrid 和 Multer 将文件附加到电子邮件
【发布时间】:2016-06-28 00:12:00
【问题描述】:

我正在尝试将文件附加到 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)

【问题讨论】:

  • 您遇到问题了吗?您是否使用 nodemailer.js 框架发送电子邮件?你能分享helper.Mail代码吗? console.log(req.body.File); 显示了什么?
  • 您能否按照@danilodeveloper 的要求提供更多信息/代码?

标签: node.js sendgrid multer


【解决方案1】:

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

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

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

【讨论】:

  • 很好,我会测试它!我想如果我循环遍历req.file 对象,它也可以处理多个文件?
  • 您必须将缓冲区转换为 base64 字符串,否则它会像 sharm 一样工作:D 谢谢! attachment.setContent(fileInfo.buffer.toString('base64'));
  • 谢谢!只需在示例中修复它。我以为 Attachment 对象可以处理 Buffer 对象,但事实并非如此。
猜你喜欢
  • 2017-08-21
  • 1970-01-01
  • 1970-01-01
  • 2020-06-27
  • 1970-01-01
  • 1970-01-01
  • 2014-07-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多