Search code examples
node.jsmandrill

How to attach a file (from url) to email using Mandrill and node request


I have a URL to an Excel file that I'm trying to add as an attachment to an email being sent out by Mandrill. Mandrill is expecting the attachment content in base64:

enter image description here

I'm trying to get the content of the Excel file, and add it to my Mandrill message, but it's not working. I need to use the native node request because I can't add a bunch of dependencies to the project as a whole.

I believe my problem is coming from my code not waiting for the request to finish, so the data variable is still blank when it's being passed to my message object. But I'm new to this, so I'm trying to figure out if there's a way to use "async/await" here to make sure my message object gets the data after the request is finished.

Any tips on what I should change here?

var https = require('https');

var data = '';
var request = https.request(myExcelFileURL, function (res) {
    res.on('data', function (chunk) {
        data += chunk;
    });
    res.on('end', function () {
        console.log(data);

    });
});
request.on('error', function (e) {
    console.log(e.message);
});
request.end();


// mandrill message
var message = {
   "html": msg,
   "subject": 'Test Excel Attachment',
   "from_email": from,
   "from_name": "Tester",
   "to": [{
          "email": email
    }],
    "headers": {
           "Reply-To": email
     },
    "attachments": [{
        "type": 'application/xlsx',
        "name": 'test.xlsx',
        "content": data.toString('base64') //this is coming up blank
     }],
};

Solution

  • The request for getting the excel file is async but you are not waiting for it to finish. You must call your message sending in the end handler of the request

    var data = '';
    var request = https.request(myExcelFileURL, function (res) {
        res.on('data', function (chunk) {
            data += chunk;
        });
        res.on('end', function () {
            console.log(data);
            sendmail(data);
        });
    });
    request.on('error', function (e) {
        console.log(e.message);
    });
    request.end();
    
    
    
    function sendmail (data){
      var message = {
       "html": msg,
       "subject": 'Test Excel Attachment',
       "from_email": from,
       "from_name": "Tester",
       "to": [{
              "email": email
        }],
        "headers": {
               "Reply-To": email
         },
        "attachments": [{
            "type": 'application/xlsx',
            "name": 'test.xlsx',
            "content": data.toString('base64')
         }],
      };
    
      //send the message
    }