Using Mailgun with NodeJS

Mailgun the popular cloud mailer has no Node.js SDK. It has a PHP SDK that can be installed with Composer.

There is a node-mailgun Node.js library which can send mail messages but it cannot send attachments.

To send attachments from a Node.js server, we call a PHP program using exec:

function sendEmailWithAttachments(sender, receiver, subject, body, attachment, callback)
{

   var cmd = "php /daemons/utility/mailgun_interface.php '" + sender + "' '" + receiver + "' '" +        subject + "' '" + body + "' " + attachment;

    exec(cmd, function(err, stdout, stderr){

         if (!err){           
              callback(true);
         }
         else{
            callback(false);
         }
    });

}

where attachement is a path to the attachment file (e.g. image) on the server.

mailgun_interface.php calls the Mailgun PHP library:

<?php

require 'vendor/autoload.php';
use Mailgun\Mailgun;

// First, instantiate the SDK with your API credentials and define your domain.
$mg = new Mailgun("yourkeyhere");
$domain = "example.com";
$from = $argv[1];
$to = $argv[2];
$subject = $argv[3];
$body = $argv[4];
$attachment = $argv[5];

// Now, compose and send your message.
$result = $mg->sendMessage($domain,
                      array(
                            'from'    => $from,
                            'to'      => $to,
                            'subject' => $subject,
                            'html'    =>
                               '' . $body .
                               ''

                           ),

                      array('attachment' =>  
                           array('@' . $attachment))
      );



  ?>