Skip to content

Mailgun

Mailgun is a transactional email service that allows developers to send, receive and track emails from web-based applications.

With Mailgun, the first 10,000 emails you send every month are free of charge!

If you wish to send an email when a specific event in your mobile app occurs, you can write a KScript method to do this, that you can call from your mobile app or use as an action in an Automation.

Ingredients

This recipe assumes that you have KScripts enabled for your app and that you have your own Mailgun account

Recipe

Expand "Backend" in the left hand menu, select "API" and then click the "KScript" button. Create a new method called something like _mailer_ and include the following JavaScript function:

function sendEmail(from, to, subject, content) {
    var client = K.http.createClient(
        'https://api:[email protected]');

    var headers = {
        'Content-type': 'multipart/form-data'
    };

    var params = {
        to: to,
        from: from,
        subject: subject,
        text: content
    };

    var result = client.post('/v3/YOUR-DOMAIN.mailgun.org/messages', params, headers);

    if (failed(result)) {
        K.log(result.error);
    }
    else if (result.isError()) {
        K.log(result.getBody());
    }

    return result;
}

You can then include your _mailer_ helper method and call the sendEmail() function from any scripts that need to send an email. To try it out, create another Kscript method called something like sendEmail, add input parameters(strings) for the from address, to address, subject and body and then paste in the following code:

include("_mailer_");

sendEmail(K.params.from, K.params.to, K.params.subject, K.params.body);

You can now test your new method and use as an action in an Automation.

Note that while your domain in your Mailgun account is in sandbox mode, you can only send emails to upto five authorized recipients

If you are using our Backend feature, you can also call this method from your mobile app or, if you wish to send a recurring email (for example a digest of recent activity), this can be scheduled to run once per hour or day.

Further reading

A full reference guide to the Mailgun API service can be found on the Mailgun docs site.

Thanks

We would like to thank Edson Iván Mendieta Moreno from Via Professional Services for contributing to this article.