Using Mailgun with Codenvy

Below are various different projects talking to Mailgun API that you can create with Codenvy Factories:

Sample 1:


Warning: file_get_contents() [function.file-get-contents]: php_network_getaddresses: getaddrinfo failed: Name or service not known in /home/content/28/10918028/html/wp-content/themes/twentytwelve/views/factory.php on line 3

Warning: file_get_contents(http://factories.codenvy-stg.com/generated/mailgun.html) [function.file-get-contents]: failed to open stream: php_network_getaddresses: getaddrinfo failed: Name or service not known in /home/content/28/10918028/html/wp-content/themes/twentytwelve/views/factory.php on line 3

Sample 2:


Warning: file_get_contents() [function.file-get-contents]: php_network_getaddresses: getaddrinfo failed: Name or service not known in /home/content/28/10918028/html/wp-content/themes/twentytwelve/views/factory.php on line 3

Warning: file_get_contents(http://factories.codenvy-stg.com/generated/mailgun1.html) [function.file-get-contents]: failed to open stream: php_network_getaddresses: getaddrinfo failed: Name or service not known in /home/content/28/10918028/html/wp-content/themes/twentytwelve/views/factory.php on line 3

Sample 3:


Warning: file_get_contents() [function.file-get-contents]: php_network_getaddresses: getaddrinfo failed: Name or service not known in /home/content/28/10918028/html/wp-content/themes/twentytwelve/views/factory.php on line 3

Warning: file_get_contents(http://factories.codenvy-stg.com/generated/mailgun2.html) [function.file-get-contents]: failed to open stream: php_network_getaddresses: getaddrinfo failed: Name or service not known in /home/content/28/10918028/html/wp-content/themes/twentytwelve/views/factory.php on line 3

Sample 4:


Warning: file_get_contents() [function.file-get-contents]: php_network_getaddresses: getaddrinfo failed: Name or service not known in /home/content/28/10918028/html/wp-content/themes/twentytwelve/views/factory.php on line 3

Warning: file_get_contents(http://factories.codenvy-stg.com/generated/mailgun3.html) [function.file-get-contents]: failed to open stream: php_network_getaddresses: getaddrinfo failed: Name or service not known in /home/content/28/10918028/html/wp-content/themes/twentytwelve/views/factory.php on line 3

 


This document will explain the details of integrating the Mailgun API into Codenvy. Mailgun API is a set of powerful APIs that allow users to send, receive and track email effortlessly. The API also allows the creation of mailing lists, campaigns so that campaign emails can be sent to multiple mail ids in a mailing list. The explanation has been done with 7 very basic Java projects that makes use of the Mailgun API through the Jersey client library to explain some basic features provided by the API.

Before proceeding to the creation of the Java projects, please register at https://mailgun.com/signup with your email id and this will generate keys which will be used for the integration. While registering, please enter a domain name which will then generate a mailgun domain name for your that will be used in the code. You can see your keys at https://mailgun.com/cp :

mailgun_apikeys

The Mailgun API has various methods to integrate with your application for various functionalities.

You can get more information about the API methods at http://documentation.mailgun.com/.

The first factory workspace source code is to explain the process of sending an email using the Mailgun API.

Create the first Project

Login to your Codenvy workspace and create a WAR project named as ‘MailgunSample’. This will have the following structure:

mailgun_structure

Create pom.xml File

To make use of the Mailgun API using the Jersey client library, we need to create a customised Java struts form and so please update the pom.xml to include the struts jars and the jersey client jars into your project as Maven dependencies :

<dependencies>
    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts2-core</artifactId>
      <version>2.2.3.1</version>
      <exclusions>
        <exclusion>
          <artifactId>tools</artifactId>
          <groupId>com.sun</groupId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts2-config-browser-plugin</artifactId>
      <version>2.2.3.1</version>
    </dependency>
    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts2-junit-plugin</artifactId>
      <version>2.2.3.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.1.1</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.5</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-mock</artifactId>
      <version>2.0.8</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>2.5</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.4</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey-client</artifactId>
      <version>1.17.1</version>
    </dependency>
    <dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey-core</artifactId>
      <version>1.17.1</version>
    </dependency>
    <dependency>
      <groupId>com.sun.jersey.contribs</groupId>
      <artifactId>jersey-multipart</artifactId>
      <version>1.17.1</version>
    </dependency>
  </dependencies>

This will include these jars in your project as follows:

mailgun_dependencies

Create Java class

Now, create a Java class named ‘MailgunSample.java’ that will send an email from your created mailgun domain to the recipients you specify in the code. This is done with the Jersey client library. All this is done inside the method execute() in the Java class:

 public String execute() throws Exception{

      Client client = Client.create();
      client.addFilter(new HTTPBasicAuthFilter("api","key-92mpls3tv4s5ywg85co7fd98lgpakij7"));

      WebResource webResource = client.resource("https://api.mailgun.net/v2/codenvy.mailgun.org" +
                               "/messages");

      MultivaluedMapImpl formData = new MultivaluedMapImpl();
      formData.add("from", "Sample User <abc@codenvy.mailgun.org>");
      formData.add("to", "abc@xyz.com");
      formData.add("subject", "Hello");
      formData.add("text", "Testing some Mailgun awesomness!");

      ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, formData);
      String output = clientResponse.getEntity(String.class);

      setMessage("Your email has been sent successfully : " + output);
      return "SUCCESS";
   }

Create index.jsp File

Your Codenvy project will have an index.jsp which submits the request to the Java class:

<%@taglib uri="/struts-tags" prefix="s" %>

<html>
<head>
<title>Mailgun Sample</title>
</head>
<body>
  <h1>Please submit to send an email</h1>
  <center><s:form action="hello" >
        <s:submit />
    </s:form></center>
</body>
</html>

Your Codenvy project will have a success.jsp which will be invoked from the MailgunSample class to display the response on the browser.

Create web.xml and struts.xml

Since this is a struts based project, so the struts mapping is defined in the web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.FilterDispatcher </filter-class>
</filter>
<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

The struts.xml maps the form action:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <package name="default" namespace="/" extends="struts-default">
        <action name="hello" class="com.codenvy.MailgunSample">
            <result name="SUCCESS">/success.jsp</result>
        </action>
    </package>
</struts>

Build and Run Your first Project

Now you build and run your Codenvy project and the submit button will be displayed in the browser:

mailgun_runapp

On submitting the form, an email is send to the mail Id defined in the ‘to’ attribute with the subject and text as defined in the Java class.

The second factory workspace source code is to explain the process of creating a maillist and then adding a sample member email id to the maillist using the Mailgun API :

Create the second Project

Login to your Codenvy workspace and create a WAR project named as ‘MailgunSample1’. This will have the same structure as the first project and the pom.xml will define the same dependencies as the first project.

Create Java class

Now, create a Java class named ‘MailgunSample.java’ that will create a mail list in your created mailgun domain and then add an email id to the maillist. This is done with the Jersey client library. All this is done inside the method execute() in the Java class:

  public String execute() throws Exception{

      Client client = Client.create();
      client.addFilter(new HTTPBasicAuthFilter("api","key-92mpls3tv4s5ywg85co7fd98lgpakij7"));

      WebResource webResource = client.resource("https://api.mailgun.net/v2/lists");

      MultivaluedMapImpl formData = new MultivaluedMapImpl();
      formData.add("address", "samplelist@codenvy.mailgun.org");
      formData.add("description", "Sample Mailgun list");

      webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, formData);

      webResource = client.resource("https://api.mailgun.net/v2/lists/" +
                               "samplelist@codenvy.mailgun.org/members");
      formData = new MultivaluedMapImpl();
      formData.add("address", "abc@xyz.com");
      formData.add("subscribed", true);
      formData.add("name", "ABC");
      formData.add("description", "Sample Member");
      formData.add("vars", "{\"age\": 26}");
      ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, formData);
      String output = clientResponse.getEntity(String.class);

      setMessage("Your list has been created successfully and a member has been added to it : " + output);
      return "SUCCESS";
   }

Create index.jsp File

Your Codenvy project will have an index.jsp similar to the first project:

Your Codenvy project will have a success.jsp which will be invoked from the MailgunSample class to display the response on the browser

The web.xml and struts.xml will be same as the first project.

Build and Run Your second Project

Now you build and run your Codenvy project and the submit button will be displayed in the browser similar to the first project.

On submitting the form, the java class creates the maillist and adds a member to the maillist. You can see this in your mailgun account:

mailgun1_output

The member email id will be seen on clicking the mail list.

The third factory workspace source code is to explain the process of sending an email to your created maillist using the Mailgun API. This will mean that all members of the maillist will receive the email :

Create the third Project

Login to your Codenvy workspace and create a WAR project named as ‘MailgunSample2’. This will have the same structure as the first project and the pom.xml will define the same dependencies as the first project.

Create Java class

Now, create a Java class named ‘MailgunSample.java’ that will send an email to your maillist. This is done with the Jersey client library. All this is done inside the method execute() in the Java class:

  public String execute() throws Exception{

      Client client = Client.create();
      client.addFilter(new HTTPBasicAuthFilter("api","key-92mpls3tv4s5ywg85co7fd98lgpakij7"));

      WebResource webResource = client.resource("https://api.mailgun.net/v2/samples.mailgun.org" +
                               "/messages");

      MultivaluedMapImpl formData = new MultivaluedMapImpl();
      formData.add("from", "Sample User <abc@codenvy.mailgun.org>");
      formData.add("to", "samplelist@codenvy.mailgun.org");
      formData.add("subject", "Hello");
      formData.add("text", "Testing some Mailgun awesomness!");

      ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, formData);
      String output = clientResponse.getEntity(String.class);
      setMessage("Your email has been sent successfully to your mailig list : " + output);
      return "SUCCESS";
   }

Create index.jsp File

Your Codenvy project will have an index.jsp similar to the first project:

Your Codenvy project will have a success.jsp which will be invoked from the MailgunSample class to display the response on the browser

The web.xml and struts.xml will be same as the first project.

Build and Run Your third Project

Now you build and run your Codenvy project and the submit button will be displayed in the browser similar to the first project.

On submitting the form, the java class sends an email to the maillist which means that each member of the maillist will receive the email.

The fourth factory workspace source code is to explain the process of creating a campaign and attach an email to the campaign using the Mailgun API :

Create the fourth Project

Login to your Codenvy workspace and create a WAR project named as ‘MailgunSample3’. This will have the same structure as the first project and the pom.xml will define the same dependencies as the first project.

Create Java class

Now, create a Java class named ‘MailgunSample.java’ that will create a campaign and attach an email message to the campaign. This is done with the Jersey client library. All this is done inside the method execute() in the Java class:

  public String execute() throws Exception{

      Client client = Client.create();
      client.addFilter(new HTTPBasicAuthFilter("api","key-92mpls3tv4s5ywg85co7fd98lgpakij7"));

      WebResource webResource = client.resource("https://api.mailgun.net/v2/codenvy.mailgun.org/campaigns");

      MultivaluedMapImpl formData = new MultivaluedMapImpl();
      formData.add("name", "Newsletter");
      formData.add("id", "12345");
      webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, formData);

      webResource = client.resource("https://api.mailgun.net/v2/codenvy.mailgun.org" +
                               "/messages");

      formData = new MultivaluedMapImpl();
      formData.add("from", "Sample User <abc@codenvy.mailgun.org>");
      formData.add("to", "samplelist@codenvy.mailgun.org");
      formData.add("subject", "Hello");
      formData.add("text", "Testing some Mailgun awesomness!");
      formData.add("o:campaign", "12345");
      ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, formData);
      String output = clientResponse.getEntity(String.class);

      setMessage("Your campaign has been created and a message has been attached to it : " + output);
      return "SUCCESS";
   }

Create index.jsp File

Your Codenvy project will have an index.jsp similar to the first project:

Your Codenvy project will have a success.jsp which will be invoked from the MailgunSample class to display the response on the browser

The web.xml and struts.xml will be same as the first project.

Build and Run Your fourth Project

Now you build and run your Codenvy project and the submit button will be displayed in the browser similar to the first project.

On submitting the form, the java class creates a campaign and attaches a message to the campaign:

mailgun3_output

The fifth factory workspace source code is to generate some stats for your campaign using the Mailgun API. This data can then be used by you and your application in various ways. These stats are also available from your mailgun account but generating the data programmatically allows you the flexibility to use it in various areas of your application :

Create the fifth Project

Login to your Codenvy workspace and create a WAR project named as ‘MailgunSample4’. This will have the same structure as the first project and the pom.xml will define the same dependencies as the first project.

Create Java class

Now, create a Java class named ‘MailgunSample.java’ that will generate the stats for the requested campaign. This is done with the Jersey client library. All this is done inside the method execute() in the Java class:

  public String execute() throws Exception{

      Client client = Client.create();
      client.addFilter(new HTTPBasicAuthFilter("api","key-92mpls3tv4s5ywg85co7fd98lgpakij7"));

      WebResource webResource = client.resource("https://api.mailgun.net/v2/codenvy.mailgun.org/campaigns/12345/stats");

      ClientResponse clientResponse = webResource.get(ClientResponse.class);
      String output = clientResponse.getEntity(String.class);

      setMessage("The stats for the campaign are : " + output);
      return "SUCCESS";
   }

Create index.jsp File

Your Codenvy project will have an index.jsp similar to the first project:

Your Codenvy project will have a success.jsp which will be invoked from the MailgunSample class to display the response on the browser.

The web.xml and struts.xml will be same as the first project.

Build and Run Your fifth Project

Now you build and run your Codenvy project and the submit button will be displayed in the browser similar to the first project.

On submitting the form, the java class will display the stats for the campaign on the browser :

mailgun4_output

The sixth factory workspace source code is to explain the process of creating a mailbox for your account to receive emails :

Create the sixth Project

Login to your Codenvy workspace and create a WAR project named as ‘MailgunSample5’. This will have the same structure as the first project and the pom.xml will define the same dependencies as the first project.

Create Java class

Now, create a Java class named ‘MailgunSample.java’ that will create the mailbox for your account under your mailgun domain. This is done with the Jersey client library. All this is done inside the method execute() in the Java class:

  public String execute() throws Exception{

      Client client = Client.create();
      client.addFilter(new HTTPBasicAuthFilter("api","key-92mpls3tv4s5ywg85co7fd98lgpakij7"));

      WebResource webResource = client.resource("https://api.mailgun.net/v2/codenvy.mailgun.org" +
                               "/mailboxes");

      MultivaluedMapImpl formData = new MultivaluedMapImpl();
      formData.add("mailbox", "samplemails@codenvy.mailgun.org");
      formData.add("password", "sample");
      ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, formData);

      String output = response.getEntity(String.class);

      setMessage("Your mailbox has been created successfully : " + output);
      return "SUCCESS";
   }

Create index.jsp File

Your Codenvy project will have an index.jsp similar to the first project:

Your Codenvy project will have a success.jsp which will be invoked from the MailgunSample class to display the response on the browser.

The web.xml and struts.xml will be same as the first project.

Build and Run Your sixth Project

Now you build and run your Codenvy project and the submit button will be displayed in the browser similar to the first project.

On submitting the form, the java class will create a mailbox in your mailgun account.

The seventh factory workspace source code is to explain the process of creating a route in your mailgun account so that emails coming into your domain can be routed to a different mailbox that you would like :

Create the seventh Project

Login to your Codenvy workspace and create a WAR project named as ‘MailgunSample6’. This will have the same structure as the first project and the pom.xml will define the same dependencies as the first project.

Create Java class

Now, create a Java class named ‘MailgunSample.java’ that will create the route for your account. This is done with the Jersey client library. All this is done inside the method execute() in the Java class:

  public String execute() throws Exception{

      Client client = Client.create();
      client.addFilter(new HTTPBasicAuthFilter("api","key-92mpls3tv4s5ywg85co7fd98lgpakij7"));

      WebResource webResource = client.resource("https://api.mailgun.net/v2/routes");

      MultivaluedMapImpl formData = new MultivaluedMapImpl();

      formData.add("description", "Sample route");
      formData.add("expression", "match_recipient('.*@codenvy.mailgun.org')");
      formData.add("action", "forward('abc@xyz.com')");

      ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, formData);
      String output = clientResponse.getEntity(String.class);

      setMessage("Your route has been created successfully : " + output);
      return "SUCCESS";
   }

Create index.jsp File

Your Codenvy project will have an index.jsp similar to the first project:

Your Codenvy project will have a success.jsp which will be invoked from the MailgunSample class to display the response on the browser.

The web.xml and struts.xml will be same as the first project.

Build and Run Your seventh Project

Now you build and run your Codenvy project and the submit button will be displayed in the browser similar to the first project.

On submitting the form, the java class will create the route in your mailgun account.

In a similar way, you can use various API methods of mailgun to perform various operations that may be required within your application.