繁体   English   中英

Node.js 使用 nodemailer 发送带有图像附件的电子邮件

[英]Node.js sending an email with image attachment using nodemailer

我正在尝试通过发布请求发送电子邮件。 我正在使用 Express 和 nodemailer。 我对“fs”感到困惑我的电子邮件正在发送,但图像未作为附件包含在内。 我检查了文档,但它们似乎都发送了静态文件,而不是从表单请求中流式传输的文件。

var smtpTransport = nodemailer.createTransport("SMTP",{
  service: "Gmail",
  auth: {
    user: "gmail_address@gmail.com",
    pass: "password_for_gmail_address"
  }
});

app.get('/', function(req, res){
    res.send('<form method="post" enctype="multipart/form-data">'
      + '<p>Post Title: <input type="text" name="title"/></p>'
      + '<p>Post Content: <input type="text" name="content"/></p>'
      + '<p>Image: <input type="file" name="image"/></p>'
      + '<p><input type="submit" value="Upload"/></p>'
      + '</form>');
  })

app.post('/', function(req, res, next){
  var mailOptions = {
    from: "gmail_address@gmail.com", // sender address
    to: "somebodyelse@example.com", // list of receivers
    subject: req.body.title, // Subject line
    text: req.body.content, // plaintext body
    attachments:[
      {
        fileName: req.body.title,
        streamSource: req.files.image
      }
    ]
  }

  smtpTransport.sendMail(mailOptions, function(error, response){
    if(error){
      console.log(error);
      res.send('Failed');
    }else{
      console.log("Message sent: " + response.message);
      res.send('Worked');
    }
  });   
});

这对我有用:

attachments: [{   // stream as an attachment
            filename: 'image.jpg',
            content: fs.createReadStream('/complete-path/image.jpg')
        }]

假设req.files.image是一个File对象,而不是一个可读流,您需要为它创建一个可以在附件中使用的读取流:

streamSource: fs.createReadStream(req.files.image.path)

而不是streamSource尝试使用contents

contents: new Buffer(req.files.image, 'base64')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM