Sending Messages Using the Mailgun Service Client in Java

MailgunClient from the com.aspose.email.services.mailgun.client package sends messages through the Mailgun API. The client connects over HTTP. To learn how to select an HTTP library, see HTTP Clients for Mail Services.

This client works with its own data model. To send a MailMessage through Mailgun, see Send Email via MailGun and SendGrid.

Sending a Message

To create a client, pass your Mailgun API key to the builder. Use MailgunMessage.create to prepare a message with one recipient and an HTML body, and then send it through your sending domain:

import com.aspose.email.services.mailgun.client.MailgunClient;
import com.aspose.email.services.mailgun.model.MailgunMessage;
import com.aspose.email.services.mailgun.model.MailgunSendResponse;

try (MailgunClient mailgun = MailgunClient.builder().apiKey("api-key").build()) {
    MailgunMessage message = MailgunMessage.create(
            "from@example.com", "to@example.com", "Weekly report", "<p>The report is ready.</p>");
    MailgunSendResponse response = mailgun.messages("mg.example.com").send(message);
    System.out.println(response.getId() + ": " + response.getMessage());
}

Other code samples on this page use the mailgun variable created here.

Selecting a Region

The client uses the US region of Mailgun by default. If your domain is in the EU region, pass MailgunClient.BASE_URL_EU to the builder:

import com.aspose.email.services.mailgun.client.MailgunClient;

MailgunClient mailgun = MailgunClient.builder()
        .apiKey("api-key")
        .baseUrl(MailgunClient.BASE_URL_EU)
        .build();

Setting Recipients and Content

To set several recipients and both text and HTML content, create the message and set its properties. To show a display name, use the Name <address> format:

import com.aspose.email.services.mailgun.model.MailgunMessage;

MailgunMessage message = new MailgunMessage();
message.setFrom("Reports Team <from@example.com>");
message.addTo("to@example.com").addTo("to2@example.com");
message.addCc("cc@example.com");
message.addBcc("bcc@example.com");
message.setReplyTo("reply@example.com");
message.setSubject("Weekly report");
message.setText("The report is ready.");
message.setHtml("<p>The report is <b>ready</b>.</p>");

mailgun.messages("mg.example.com").send(message);

Adding Attachments

Create a MailgunAttachment object with the file name, the data and the content type. To add an image that the HTML body displays, use MailgunAttachment.inline, and then refer to its file name with the cid: prefix:

import com.aspose.email.services.mailgun.model.MailgunAttachment;
import com.aspose.email.services.mailgun.model.MailgunMessage;
import java.nio.file.Files;
import java.nio.file.Paths;

byte[] report = Files.readAllBytes(Paths.get("report.pdf"));
byte[] logo = Files.readAllBytes(Paths.get("logo.png"));

MailgunMessage message = MailgunMessage.create("from@example.com", "to@example.com",
        "Weekly report", "<p><img src=\"cid:logo.png\"> The report is attached.</p>");
message.addAttachment(new MailgunAttachment("report.pdf", report, "application/pdf"));
message.addAttachment(MailgunAttachment.inline("logo.png", logo, "image/png"));

mailgun.messages("mg.example.com").send(message);

Setting Delivery Options

The following options control how Mailgun processes a message:

Method Description
addTag Adds a tag for Mailgun statistics.
setTrackingClicks Turns click tracking on or off for this message.
setTrackingOpens Turns open tracking on or off for this message.
setDeliveryTime Schedules delivery. The value is a date in the RFC 2822 format.
setTestMode When set to true, Mailgun accepts the message but does not deliver it.

If you do not set the tracking options, the client does not send them, and the tracking settings of your Mailgun domain apply. getTrackingClicks and getTrackingOpens return null in this case. A value that you set takes priority over the domain setting for this message:

import com.aspose.email.services.mailgun.model.MailgunMessage;

MailgunMessage message = MailgunMessage.create(
        "from@example.com", "to@example.com", "Weekly report", "<p>The report is ready.</p>");
message.addTag("reports");
message.setTrackingClicks(false);
message.setTrackingOpens(false);
message.setDeliveryTime("Fri, 25 Oct 2030 23:10:10 -0000");
message.setTestMode(true);

mailgun.messages("mg.example.com").send(message);

Sending a MIME Message

If you already have a complete message in the MIME format, pass it to sendMime with a comma-separated list of recipients. The method sends the text as UTF-8:

import com.aspose.email.services.mailgun.model.MailgunSendResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

String mime = new String(Files.readAllBytes(Paths.get("message.eml")), StandardCharsets.UTF_8);
MailgunSendResponse response = mailgun.messages("mg.example.com").sendMime("to@example.com", mime);
System.out.println(response.getId());

Handling Errors

When Mailgun returns an error status, the client throws HttpClientException, which contains the status and the response body. The exception extends java.io.IOException, which the client also throws for connection failures.

import com.aspose.email.services.mailgun.client.MailgunClient;
import com.aspose.email.services.mailgun.model.MailgunMessage;
import com.aspose.ext.http.HttpClientException;

try (MailgunClient mailgun = MailgunClient.builder().apiKey("invalid-api-key").build()) {
    mailgun.messages("mg.example.com").send(MailgunMessage.create(
            "from@example.com", "to@example.com", "Weekly report", "<p>The report is ready.</p>"));
} catch (HttpClientException e) {
    System.out.println(e.getStatusCode() + ": " + e.getResponseBody());
}