skip to Main Content

I have a form in which has an upload file input. I want the user to be able to upload their file and send it via the form. At the moment the PDF file shows attached in the email but doesn’t contain any data and won’t open etc.

This is what I currently have within the nodemailer options:

let mailOptions = {
    from: '"Macwear Clothing" <[email protected]>', // 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'
  }]
};

Client Side index.ejs file

<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" <[email protected]>', // 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: <[email protected]>
    // 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

Answers


  1. Chosen as BEST ANSWER

    I simply used Multer to handle the uploading of the file. All that was required was to set the multer upload directory.

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

    And then within the /send route add in upload.single('needle') and remove the arrow function:

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

    Then within the attachments in mailOptions:

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

    Lastly it is important to set the enctype on the HTML form to multipart/form-data otherwise the file upload via multer will not work.


  2. you using path for both your attachment and static path so the document will not display its extension

    try:

    app.use(express.static('public'))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search