Email Tracking using MailGun with Grails application

24 / Jul / 2014 by Vivek Garg 1 comments

Many times we need to track whether the email is open/deliver/read by users, sent from our application. After analyzing, I concluded that MailGun provides email tracking services that i used with my grails application and thought it worth sharing.

There are two ways to send messages using MailGun:

#1. HTTP API
#2. SMTP

I have used HTTP API and MailGun uses Jersey Request Builder.So, add following dependency:

compile ":jersey-request-builder:1.2.1"

The steps involved in using MailGun by Rackspace in our grails application are as:-

#1.SignUp With MailGun:

SignUp with Mailgun HERE and you will get the following code.

public static ClientResponse SendSimpleMessage() {
    Client client = Client.create();
    client.addFilter(new HTTPBasicAuthFilter("api",
                "${YOUR_API_KEY}"));
    WebResource webResource =
        client.resource("https://api.mailgun.net/v2/${YOUR_MAILGUN_SUB_DOMAIN}/messages");
    MultivaluedMapImpl formData = new MultivaluedMapImpl();
    formData.add("from", "Mailgun Sandbox <postmaster@${YOUR_MAILGUN_SUB_DOMAIN}>");
    formData.add("to", "${EMAIL_ID_YOU_WANT_TO_SEND_TO}");
    formData.add("subject", "Hello ${ACCOUNT_NAME_YOU_REGISTERED_WITH}");
    formData.add("text", "Congratulations ${ACCOUNT_NAME_YOU_REGISTERED_WITH}, you just sent an email with Mailgun!  You are truly awesome!  You can see a record of this email in your logs: https://mailgun.com/cp/log .  You can send up to 300 emails/day from this sandbox server.  Next, you should add your own domain so you can send 10,000 emails/month for free.");
    return webResource.type(MediaType.APPLICATION_FORM_URLENCODED).
                                                post(ClientResponse.class, formData);
}

#2.Log In to MailGun here and go to Logs section.And enter a call back url on which mailgun let’s you know about Delivery of messages and also you can a enter a call back for failed messages, as can be seen in following image:

ForMailGunDelivery CallBack

#3.Similary go to Tracking section.And enter a call back url on which mailgun let’s you know about Opens event of messages and also you can a enter a call back for Clicks event messages, as can be seen in following image:

ForMailGunOpenedCallBack

#4.Add following actions to send mails through MailGun and to handle callBacks provided to MailGun.

a) action to send mail-

  def sendSimpleMessage() {
        log.debug "::::Exceuting mail::::"
        Client client = Client.create();
        client.addFilter(new HTTPBasicAuthFilter("api",
                "${grailsApplication.config.mailGun.api}"));
        WebResource webResource =
                client.resource("${grailsApplication.config.mailGun.webResource}");
        MultivaluedMapImpl formData = new MultivaluedMapImpl();
        formData.add("from", "${grailsApplication.config.mailGun.mail.from}");
        formData.add("to", "${EMAIL_ID_YOU_WANT_TO_SEND_TO}");
        formData.add("subject", "Hello MediaIQ");
        formData.add("text", "Congratulations, you just sent an email with Mailgun!");
        //use html instead text for sending html content 
        formData.add("o:tracking", true);   
        //Set this to true to track opens event
        webResource.type(MediaType.APPLICATION_FORM_URLENCODED).
                post(ClientResponse.class, formData);
        render "success"
    }

b) action to handle delivery call back-

    def mailDeliveryCallBack() {
        boolean isMailSent = false
        List headerData = (JSON.parse(params.get("message-headers").toString())) as List
        headerData.each { List header ->
            if (header[0] == "Received") {
                isMailSent = true
              } else if (header[0] == "To") {
                User user = User.findByEmail(header[1].toString())
                user.isMailSent = true
                user.save()
              }
        }
    }

b) action to handle opens call back-

    def mailOpenedCallBack() {
        boolean isMailOpened = false
        isMailOpened = params.get("event").toString().equals("opened")
        User user = User.findByEmail(params.get("recipient").toString())
        user.isMailOpened = isMailOpened
        user.save()
    }
}

This worked for me.
Hope it helps.

Useful Links:

http://documentation.mailgun.com/user_manual.html

Cheers!!!
Vivek Garg
vivek.garg@intelligrape.com
www.intelligrape.com
My LinkedIn
MORE BLOGS BY ME

FOUND THIS USEFUL? SHARE IT

comments (1 “Email Tracking using MailGun with Grails application”)

Leave a comment -