SendGrid is a trusted email delivery service that allows developers to send both transactional and marketing emails.

With SendGrid, you can send 100 emails each day 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 SendGrid 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:

// {
//     "personalizations": [{
//         "to": [{
//             "email": "[email protected]"
//         }]
//     }],
//     "from": {
//         "email": "[email protected]"
//     },
//     "subject": "Sending with SendGrid is Fun",
//     "content": [{
//         "type": "text/plain",
//         "value": "...and easy to do anywhere!"
//     }]
// }
function sendEmail(from, to, subject, content) {
    var client = K.http.createClient('https://api.sendgrid.com');
    var API_KEY = 'YOUR_SENDGRID_API_KEY';

    var headers = {
        'Authorization' : 'Bearer ' + API_KEY,
        'Content-Type': 'application/json'
    };

    var data =  {
        "personalizations": [{
            "to": [{
                "email": to
            }]
        }],
        "from": {
            "email": from
        },
        "subject": subject,
        "content": [{
            "type": "text/plain",
            "value": content
        }]
    };

    var result = client.post('/v3/mail/send', K.JSON.stringify(data), 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.

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 SendGrid API service can be found on the SendGrid website.