通过HTML表单使用nodemailer发送PDF文件

时间:2018-08-10 22:01:29

标签: html node.js express nodemailer

我有一个带有输入上传文件的表格。我希望用户能够上传他们的文件并通过表格发送它。目前,PDF文件显示为电子邮件中的附件,但不包含任何数据,也无法打开等。

这是我目前在nodemailer选项中拥有的:

let mailOptions = {
    from: '"Macwear Clothing" <shop@macwearclothing.com>', // sender address
    to: req.body.email, // list of receivers
    subject: 'Order Review', // Subject line
    text: 'Order Acception', // plain text body
    html: output, // html body
    attachments: [{'filename': 'needlesheet.pdf', 'content': req.body.needle, 'contentType': 'application/pdf'
  }]
};

客户端index.ejs文件

       <div class="fileUpload up<%= item.number %>" id="m<%= item.number %>">
            <div class="fileUploadContent">
                <h2>Customer:
                    <%= item.email %>
                </h2>
                <div class="uploadFile">
                    <input id="needle" type="file" name="needle" value="Upload File &gt;">
                </div>
                <form method="POST" action="send" name="sendNeedleSheet" enctype="multipart/form-data">
                    <div class="optionalMessage">
                        <span>Optional Message:</span>
                        <textarea class="customTextArea" name="message"></textarea>
                        <input id="email" name="email" type="hidden" value="<%= item.email %>">
                    </div>
                    <div class="modalOptions">
                        <div class="mButton ok">
                            <button class="customButton" type="submit">Send</button>
                        </div>
                        <div class="mButton cancel">
                            <span>Cancel</span>
                        </div>
                    </div>
                </form>
            </div>
        </div>

app.js

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const chalk = require('chalk');
const nodemailer = require('nodemailer');
const multer = require('multer');
const app = express();

//View Engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// Body Parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));

// Set Static Path
app.use(express.static(path.join(__dirname, '/public')));

// Call JSON

//requestLoop();


// var shopifyAPI = require('shopify-node-api');
// var Shopify = new shopifyAPI({
//   shop: 'macwear-clothing-embroidery.myshopify.com', // MYSHOP.myshopify.com
//   shopify_api_key: '', // Your API key
//   access_token: '' // Your API password
// });


var orderData = null;



// Shopify.get('/admin/orders.json', function(err, data, res, headers){
//   app.locals.jsonOrderData = data;
// });

// Shopify.get('/admin/orders/count.json', function(err, data, headers) {
//   app.locals.jsonOrderCount = data;
// });

var requestLoop = setInterval(function () {

  var request = require("request");

  var options_orders = {
    method: 'GET',
    url: 'https://macwear-clothing-embroidery.myshopify.com/admin/orders.json',
    headers: {
      'Postman-Token': '',
      'Cache-Control': 'no-cache',
      Authorization: ''
    }
  };

  var options_order_count = {
    method: 'GET',
    url: 'https://macwear-clothing-embroidery.myshopify.com/admin/orders/count.json',
    headers: {
      'Postman-Token': '',
      'Cache-Control': 'no-cache',
      Authorization: ''
    }
  };


  request(options_orders, function (error, response, body) {
    if (error) throw new Error(error);
    jsonOrderData = JSON.parse(body);
    //console.log(body);
  });

  request(options_order_count, function (error, response, body) {
    if (error) throw new Error(error);
    jsonOrderCount = JSON.parse(body);
    //console.log(body);
  });

}, 60000);


app.get('/shopifycall_order_count', function (req, res) {
  res.send(jsonOrderCount);
  //res.render('dynamic_content');
});

app.get('/shopifycall_orders', function (req, res) {
  res.render('dynamic_content');
});

// Multer File Processing


app.post('/send', (req, res) => {
  const output = `
      <p>Please View & Accpet or Reject the PDF</p>
  `;

let transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 587,
    secure: false, // true for 465, false for other ports
    auth: {
        user: '',
        pass: ''
    },
    tls:{
      rejectUnauthorized:false
    }
});

// setup email data with unicode symbols
let mailOptions = {
    from: '"Macwear Clothing" <shop@macwearclothing.com>', // sender address
    to: req.body.email, // list of receivers
    subject: 'Order Review', // Subject line
    text: 'Order Acception', // plain text body
    html: output, // html body
    attachments: [{'filename': 'needlesheet.pdf', 'content': req.body.needle, 'contentType': 'application/pdf'
  }]
};

// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        return console.log(error);
    }
    console.log('Message sent: %s', info.messageId);
    // Preview only available when sending through an Ethereal account
    console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));

    // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>
    // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
});

console.log(req.body.needle);

});




app.get('/', (req, res) => {
  res.render('index');
});

app.listen(3000, () => {
  console.log('Starting MOS.......');
  console.log(chalk.green('Loaded on port 3000'));
  console.log('Fetching API.......');
  console.log('Initial API Request will take 60 Seconds');
});

2 个答案:

答案 0 :(得分:0)

我只是使用Multer处理文件的上传。所需要做的就是设置multer上传目录。

var upload = multer({dest: './public/uploads/'});

然后在/ send路由中,添加upload.single('needle')并删除箭头功能:

app.post('/send', upload.single('needle'), function (req, res, next) {

});

然后在mailOptions的附件中:

attachments: [
  {
      filename: req.file.originalname,
      path: req.file.path

  }

]

最后,将HTML表单上的enctype设置为multipart / form-data很重要,否则通过multer上传的文件将无法工作。

答案 1 :(得分:0)

您对附件和静态路径都使用了路径,因此文档不会显示其扩展名

试试:

app.use(express.static('public'))