如何使用nodemailer从上传按钮发送附件

时间:2020-08-25 08:26:43

标签: html forms handlebars.js nodemailer

我正在尝试创建一个表单,供用户填写以及通过输入标签上传图片或docx文件的网站。我正在使用控制器,因为为此我也使用hbs。

const output = `<p>You have a new message from the TIPH website<p>
    <h3>Contact Details</h3>
    <p>Name: ${req.body.contact_name}<p>
    <h3>Inquiry</h3>
    <p>${req.body.contact_inquiry}</p>
    `;
    
    var transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
          user: process.env.EMAIL,
          pass: process.env.PASSWORD
        }
      });
      
      var mailOptions = {
        from: `${req.body.contact_email}`,
        to: '...',
        subject: `${req.body.contact_subject}`,
        html: output,
        attachments: [
            {
                filename: `${req.body.contact_upload}`,
            }
        ]
      };
      
      transporter.sendMail(mailOptions, function(error, info){
        if (error) {
          console.log(error);
        } else {
          console.log('Email sent: ' + info.response);
          res.render('contact-us', {
            layout: '/layouts/main',
            title: 'Contact Us',
            contact_active: true,
            msg: 'Your message has been sent!'
        })
        }
      });

1 个答案:

答案 0 :(得分:1)

为了将文件上传到节点服务器,您应该将HTML表单元素的enctype属性设置为enctype="multipart/form-data"

要使用文件服务器端,可以使用FAQs。该中间件可以从req.file属性中获取上传的文件。

然后可以将此文件添加到attachments数组中。您可以在multer中找到需要发送给Nodemailer的道具。