Java - Sending Email Using Mandrill Example

Do you need to send email using Mandrill from Java application? This tutorial gives you a simple example how to do so including how to set subject, content, sender email & name, recipient list and include attachments.

Dependencies

While Mandrill have documented their APIs, it would be easier if we can use library for calling their APIs. Unfortunately they don't provide official library for Java, but there is a library we can use. Add the following to the <dependencies> section of your pom.xml file if you use maven.

  <dependency>
      <groupId>com.cribbstechnologies.clients</groupId>
      <artifactId>mandrillClient</artifactId>
      <version>1.1</version>
  </dependency>

If you're using gradle, here's the equivalent code.

  // https://mvnrepository.com/artifact/com.cribbstechnologies.clients/mandrillClient
  compile group: 'com.cribbstechnologies.clients', name: 'mandrillClient', version: '1.1'

If you need to attach files, the following dependency will make it easier to convert the file into base64 value which is required.

  <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
  <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.6</version>
  </dependency>

And for those using gradle:

  compile group: 'commons-io', name: 'commons-io', version: '2.6'

Code Example

In order to use that Mandrill client, we are going to create a helper. In using the client for sending messages, we need to create an instance of MandrillMessagesRequest and configure it. Beforehand, we need to configure MandrillConfiguration, MandrillRESTRequest, HttpClient and ObjectMapper.

Below, we also provide sendMessage method. The usage example will be given afterwards.

MandrillHelpers.java

  package com.woolha.example.helpers;

  import com.cribbstechnologies.clients.mandrill.exception.RequestFailedException;
  import com.cribbstechnologies.clients.mandrill.model.MandrillAttachment;
  import com.cribbstechnologies.clients.mandrill.model.MandrillHtmlMessage;
  import com.cribbstechnologies.clients.mandrill.model.MandrillMessageRequest;
  import com.cribbstechnologies.clients.mandrill.model.MandrillRecipient;
  import com.cribbstechnologies.clients.mandrill.model.response.message.SendMessageResponse;
  import com.cribbstechnologies.clients.mandrill.request.MandrillMessagesRequest;
  import com.cribbstechnologies.clients.mandrill.request.MandrillRESTRequest;
  import com.cribbstechnologies.clients.mandrill.util.MandrillConfiguration;
  import com.fasterxml.jackson.databind.ObjectMapper;
  import org.apache.http.client.HttpClient;
  import org.apache.http.impl.client.DefaultHttpClient;
  
  import java.util.HashMap;
  import java.util.List;
  import java.util.Map;

  public class MandrillHelpers {
  
      private static final String API_VERSION = "1.0";
      private static final String BASE_URL = "https://mandrillapp.com/api";
      private static final String MANDRILL_API_KEY = "ABCDE";
  
      private static MandrillRESTRequest request = new MandrillRESTRequest();
      private static MandrillConfiguration config = new MandrillConfiguration();
      private static MandrillMessagesRequest messagesRequest = new MandrillMessagesRequest();
      private static HttpClient client = new DefaultHttpClient();
      private static ObjectMapper mapper = new ObjectMapper();
  
      public MandrillHelpers() {
          config.setApiKey(MANDRILL_API_KEY);
          config.setApiVersion(API_VERSION);
          config.setBaseURL(BASE_URL);
          request.setConfig(config);
          request.setObjectMapper(mapper);
          request.setHttpClient(client);
          messagesRequest.setRequest(request);
      }

      public SendMessageResponse sendMessage(
              String subject,
              MandrillRecipient[] recipients,
              String senderName,
              String senderEmail,
              String content,
              List<MandrillAttachment> attachments
      ) throws RequestFailedException {
          MandrillMessageRequest mmr = new MandrillMessageRequest();
          MandrillHtmlMessage message = new MandrillHtmlMessage();
  
          Map<String, String> headers = new HashMap<String, String>();
          message.setFrom_email(senderEmail);
          message.setFrom_name(senderName);
          message.setHeaders(headers);
  
          message.setHtml(content);
          message.setSubject(subject);
          message.setAttachments(attachments);
          message.setTo(recipients);
          message.setTrack_clicks(true);
          message.setTrack_opens(true);
          mmr.setMessage(message);
  
          return messagesRequest.sendMessage(mmr);
      }
  }

If you want to send file as attachment, it must be encoded to base64 first. Below is a utility that takes a file path and returns base64 of the file.

FileUtils.java

  package com.woolha.example.utils;
  
  import org.apache.commons.codec.binary.Base64;
  
  import java.io.File;
  import java.io.IOException;
  import java.nio.charset.StandardCharsets;
  
  public class FileUtils {
      public static String encodeFileToBase64String(String fileName) throws IOException {
          File file = new File(fileName);
          byte[] encoded = Base64.encodeBase64(org.apache.commons.io.FileUtils.readFileToByteArray(file));
          return new String(encoded, StandardCharsets.US_ASCII);
      }
  }
  

And here's the example how to use sendMessage method above.

  import com.cribbstechnologies.clients.mandrill.exception.RequestFailedException;
  import com.cribbstechnologies.clients.mandrill.model.MandrillAttachment;
  import com.cribbstechnologies.clients.mandrill.model.MandrillRecipient;
  import com.woolha.example.helpers.MandrillHelpers;
  import com.woolha.example.utils.FileUtils;
  
  import java.io.IOException;
  import java.util.ArrayList;
  import java.util.List;
  
  public class MandrillExample {
      public static void main(String[] args) {
          MandrillHelpers mandrillHelpers = new MandrillHelpers();
  
          List<MandrillAttachment> attachments = new ArrayList<>();
  
          String fileName = "file.xlsx";
  
          MandrillRecipient[] recipients = {
                  new MandrillRecipient(
                          "Recipient1",
                          "test@yahoo.com"
                  ),
                  new MandrillRecipient(
                          "Recipient2",
                          "test2@yahoo.com"
                  )
          };
  
          try {
              attachments.add(new MandrillAttachment("application/vnd.ms-excel", fileName, FileUtils.encodeFileToBase64String(fileName)));
          } catch (IOException e) {
              e.printStackTrace();
          }
  
          try {
              mandrillHelpers.sendMessage(
                      "The email subject",
                      recipients,
                      "Woolha.com",
                      "woolha.official@gmail.com",
                      "Trying to send email using Java",
                      attachments
              );
          } catch (RequestFailedException e) {
              e.printStackTrace();
          }
      }
  }