Skip to content

Instantly share code, notes, and snippets.

@itayher
Last active February 21, 2023 11:15
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itayher/148c69bd01d004d52df59bd965249884 to your computer and use it in GitHub Desktop.
Save itayher/148c69bd01d004d52df59bd965249884 to your computer and use it in GitHub Desktop.
Example how to send email with attachment in Mandrill using Backand node.js server side action

Example how to send email with attachment in Mandrill using Backand node.js server side action

Installations

  1. Create new node.js on-demand action
  2. Create acction in Mandrill and copy the API KEY
  3. Follow the instruciton by running npm backand and 'backand action deploy' command

Code Update

In index.js file add these lines before 'exports.backandCallback' function.

var mandrill = require('node-mandrill')('kPE24YlgNINqzULeTzlkJw');
var request = require('request').defaults({ encoding: null });

You need to replace kPE24YlgNINqzULeTzlkJw with your api key

In the backandCallback function have the follwoing code:

    var filePath = 'https://files.backand.io/prod13021/fb-600x300.jpg';
    var fileName = 'fb-600x300.jpg';

    request.get(filePath, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        //console.log(data);
        sendEmail(fileName, response.headers["content-type"], new Buffer(body).toString('base64'));
      }
    });

    function sendEmail(fileName, fileType, fileContent) {
      mandrill('/messages/send', {
        message: {
          to: [{email: 'itay@backand.com', name: 'Itay'}],
          from_email: 'itay@backand.com',
          subject: "Hey, what's up?",
          text: "Hello, I sent this message using mandrill.",
          attachments: [{
            "type": fileType,
            "name": fileName,
            "content": fileContent
          }]
        }
      }, function (error, res) {
        //uh oh, there was an error
        if (error) {
          //console.log(JSON.stringify(error));
          //response(error, null);
          response(error, null);
        }
        //everything's good, lets see what mandrill said
        else {
          console.log(res);
          response(null, res);
        }


      });
    }

Configuration

Update all details of the email, and use 'parameters' in order to send it in from the API or database

Test

In order to debug and run it locally call node debug.js

Deployment

Follow the instruction in Backand on-demand action UI, and run 'backand action deploy' command

Run client side

Use backand SDK to call the on-demand action in order to send the email (action name: 'sendattachment'):

  return Backand.object.action.get("items", "sendattachment", {
    "parameters": {}
  })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment