Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何使用Sendgrid和Multer将文件附加到电子邮件_Node.js_Sendgrid_Multer - Fatal编程技术网

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

Node.js 如何使用Sendgrid和Multer将文件附加到电子邮件,node.js,sendgrid,multer,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);

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

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

  • multer
    库将整个文件内容存储在
    缓冲区中的内存中
    对象(不是
  • Sendgrid库不支持
但您可以使用返回的附件来实现它,如:

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);
  /* ... */
});

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

您是否面临问题?您是否使用nodeEmailer.js框架发送电子邮件?你能分享
helper.Mail
code吗?什么
console.log(req.body.File)显示?你能按照@danilodeveloper的要求提供更多信息/代码吗?很好,我会测试它!如果我循环通过
req.file
对象,我想它也可以处理多个文件?你必须将缓冲区转换为base64字符串,否则它会像sharm:D一样工作谢谢<代码>附件.setContent(fileInfo.buffer.toString('base64')谢谢!只需在示例中修复它。我假设
Attachment
对象要处理
Buffer
对象,但它没有。