Java SDK for integrating with Mailgun
Go to file
szagr bb746c9ecf 1.0.9-SNAPSHOT 2023-05-25 13:50:21 +03:00
src release 1.0.8 2023-05-25 13:48:58 +03:00
.gitignore first commit 2022-04-09 16:12:07 +03:00
.travis.yml Create Mailgun Java SDK 2022-04-10 12:39:47 +03:00
CHANGELOG.md release 1.0.8 2023-05-25 13:48:58 +03:00
LICENSE.txt Create Mailgun Java SDK 2022-04-10 12:39:47 +03:00
README.md release 1.0.8 2023-05-25 13:48:58 +03:00
pom.xml 1.0.9-SNAPSHOT 2023-05-25 13:50:21 +03:00

README.md

Mailgun Java SDK

Build Status maven central License

The Mailgun Java SDK enables Java developers to work with Mailgun API efficiently.

Table of contents

Release notes

Changes to the SDK beginning with version 1.0.1 (June 2022) are tracked in CHANGELOG.md.

Getting Started

Requirements

To run the SDK, you will need Java 1.8+.

Install the SDK

The recommended way to use the Mailgun Java SDK in your project:

Choose version you need

Maven.

Add the following to your pom.xml:

<dependencies>
  ...
  <dependency>
    <groupId>com.mailgun</groupId>
    <artifactId>mailgun-java</artifactId>
    <version>1.0.8</version>
  </dependency>
  ...
</dependencies>

Gradle Groovy DSL .

implementation 'com.mailgun:mailgun-java:1.0.8'

Authentication

When you Sign up, Mailgun generates a primary account API key.

To view your primary account API key in the Mailgun dashboard, click on Settings on the left-hand nav in the Mailgun dashboard and then API Keys and click on the eye icon next to API_KEYS.

Base URL

Mailgun allows sending and receiving an email in either our US or our EU regions.

Be sure to use the appropriate Base URL based on which region you've created your domain in.

For domains created in our US region, the base URL (DEFAULT_BASE_URL) is:

https://api.mailgun.net/

For domains created in our EU region, the base URL (EU_BASE_URL) is:

https://api.eu.mailgun.net/

Domains

Your Mailgun account may contain multiple sending domains.

Most API URLs must include the name of the domain you're interested in.

For example:

mailgunMessagesApi.sendMessage(YOUR_DOMAIN, message);

Setup Client

Client Configuration

Configuration examples

Default Mailgun Client configuration:

//        For US servers
        MailgunClient.config(PRIVATE_API_KEY)
                
//        For EU servers        
        MailgunClient.config(EU_BASE_URL, PRIVATE_API_KEY)

Custom Mailgun client configuration.

You can specify your own logLevel, retryer, logger, errorDecoder, options.

        MailgunClient.config(PRIVATE_API_KEY)
                .logLevel(Logger.Level.NONE)
                .retryer(new Retryer.Default())
                .logger(new Logger.NoOpLogger())
                .errorDecoder(new ErrorDecoder.Default())
                .options(new Request.Options(10, TimeUnit.SECONDS, 60, TimeUnit.SECONDS, true))

Mailgun client configuration example for the Mailgun sending emails API

        MailgunMessagesApi mailgunMessagesApi = MailgunClient.config(PRIVATE_API_KEY)
            .createApi(MailgunMessagesApi.class);

Async Mailgun client configuration example for the Mailgun sending emails API

        MailgunMessagesApi mailgunAsyncMessagesApi = MailgunClient.config(PRIVATE_API_KEY)
            .createAsyncApi(MailgunMessagesApi.class);

Spring Bean Mailgun client configuration example:

        @Bean
        public MailgunMessagesApi mailgunMessagesApi() {
            return MailgunClient.config(PRIVATE_API_KEY)
                      .createApi(MailgunMessagesApi.class);
        }

Hint: register Mailgun API Client as a Singleton and reuse it while sending emails to reduce resource consumption

Responses

Each method that returns a specific JavaBean class is duplicated with the method with suffix ending with FeignResponse returns a Feign response.

You can use methods that return a specific JavaBean class:

        MessageResponse messageResponse = mailgunMessagesApi.sendMessage(YOUR_DOMAIN, message);

Or FeignResponse:

        Response feignResponse = mailgunMessagesApi.sendMessageFeignResponse(YOUR_DOMAIN, message);

From FeignResponse you can get:

//        status code
        int statusCode = feignResponse.status();
//        Headers
        Map<String, Collection<String>> headers = feignResponse.headers();
//        Protocol version
        Request.ProtocolVersion protocolVersion = feignResponse.protocolVersion();
//        etc.

More information:

Feign HTTP Response

Feign Java client

But Feign does not have the functionality to deserialize responses out of the box.

To retrieves a JavaBean class from the FeignResponse you can use decode method:

        MessageResponse messageResponse = ObjectMapperUtil.decode(feignResponse, MessageResponse.class);

Or

        JsonNode jsonNode = ObjectMapperUtil.decode(feignResponse, JsonNode.class);

Exception handling

FeignException - origin exception type for all HTTP Apis.

From FeignException you can get:

        try {
            MessageResponse messageResponse = mailgunMessagesApi.sendMessage(YOUR_DOMAIN, message);
        } catch (FeignException exception) {
//          Exception message
            String exceptionMessage = exception.getMessage();
//          status code                
            int statusCode = exception.status();
//          Headers
            Map<String, Collection<String>> headers = exception.headers();
//          etc.

More information: FeignException

Methods

Request examples

Messages

MailgunMessagesApi allows you to send emails.

Mailgun Messages documentation.

When you submit messages for delivery, Mailgun places them in a message queue.

Set up MailgunMessagesApi

        MailgunMessagesApi mailgunMessagesApi = MailgunClient.config(PRIVATE_API_KEY)
                .createApi(MailgunMessagesApi.class);

Send email

        Message message = Message.builder()
                .from(EMAIL_FROM)
                .to(USER_EMAIL)
                .subject(SUBJECT)
                .text(TEXT)
                .build();

        MessageResponse messageResponse = mailgunMessagesApi.sendMessage(DOMAIN, message);

Send email (name with email)

        Message message = Message.builder()
                .from(EMAIL_FROM)
                .to(EmailUtil.nameWithEmail(USER_NAME, USER_EMAIL))
                .subject(SUBJECT)
                .text(TEXT)
                .build();

        MessageResponse messageResponse = mailgunMessagesApi.sendMessage(DOMAIN, message);

Send email(s)

        Message message = Message.builder()
                .from(EMAIL_FROM)
                .to(Arrays.asList(USER_EMAIL_1, USER_EMAIL_2))
                .subject(SUBJECT)
                .text(TEXT)
                .build();

        MessageResponse messageResponse = mailgunMessagesApi.sendMessage(DOMAIN, message);

or

        Message message = Message.builder()
                .from(EMAIL_FROM)
                .to(USER_EMAIL_1)
                .to(USER_EMAIL_2)
                .subject(SUBJECT)
                .text(TEXT)
                .build();

        MessageResponse messageResponse = mailgunMessagesApi.sendMessage(DOMAIN, message);

Async send email(s)

Default Async Mailgun Client configuration:

        MailgunMessagesApi mailgunAsyncMessagesApi = MailgunClient.config(PRIVATE_API_KEY)
        .client(asyncClient)
        .createAsyncApi(MailgunMessagesApi.class);

Custom Async Mailgun Client configuration:

        ExecutorService executor = Executors.newFixedThreadPool(2);
        AsyncClient.Default<Object> asyncClient = new AsyncClient.Default<>(
        new Client.Default(null, null), executor);

        MailgunMessagesApi mailgunAsyncMessagesApi = MailgunClient.config(PRIVATE_API_KEY)
        .client(asyncClient)
        .createAsyncApi(MailgunMessagesApi.class);

Your can create your own implementation of feign AsyncClient.

Asynchronously send email(s).

        Message message = Message.builder()
                .from(EMAIL_FROM)
                .to(USER_EMAIL)
                .subject(SUBJECT)
                .text(TEXT)
                .build();

        CompletableFuture<MessageResponse> result = mailgunAsyncMessagesApi.sendMessageAsync(MAIN_DOMAIN, message);

Send email (html example)

        Message message = Message.builder()
                .from(EMAIL_FROM)
                .to(EMAIL_TO)
                .subject(SUBJECT)
                .html("<html>\n" +
                "<body>\n" +
                "\t<h1>Sending HTML emails with Mailgun</h1>\n" +
                "\t<p style=\"color:blue; font-size:30px;\">Hello world</p>\n" +
                "\t<p style=\"font-size:30px;\">More examples can be found <a href=\"https://documentation.mailgun.com/en/latest/api-sending.html#examples\">here</a></p>\n" +
                "</body>\n" +
                "</html>")
                .build();

        MessageResponse messageResponse = mailgunMessagesApi.sendMessage(DOMAIN, message);

Send email (attachments example)

        Message message = Message.builder()
                .from(EMAIL_FROM)
                .to(EMAIL_TO)
                .subject(SUBJECT)
                .text(TEXT)
                .attachment(new File("/path/to/file_1"))
                .attachment(new File("/path/to/file-2"))
                .attachment(Arrays.asList(new File("/path/to/file_3"), new File("/path/to/file_4")))
                .build();

        MessageResponse messageResponse = mailgunMessagesApi.sendMessage(DOMAIN, message);

Send email (attachment FormData example)

        Message message = Message.builder()
                .from(EMAIL_FROM)
                .to(EMAIL_TO)
                .subject(SUBJECT)
                .text(TEXT)
                .formData(new FormData("image/png", "filename.png", pngByteArray))
                .formData(new FormData("text/plain", "filename.txt", txtByteArray))
                .formData(Arrays.asList(
                    new FormData("image/jpeg", "filename.jpeg", jpegByteArray),
                    new FormData("text/plain", "filename.txt", txtByteArray)
                    ))
                .build();

        MessageResponse messageResponse = mailgunMessagesApi.sendMessage(DOMAIN, message);

Send email (inline multiple files example)

        Message message = Message.builder()
                .from(EMAIL_FROM)
                .to(EMAIL_TO)
                .subject(SUBJECT)
                .html("Text above images." +
                "<div><img height=200 id=\"1\" src=\"cid:mailgun_logo.png\"/></div>" +
                "Text between images." +
                "<div><img id=\"2\" src=\"cid:test_images.jpeg\"/></div>" +
                "Text below images.")
                .inline(MAILGUN_LOGO_FILE)
                .inline(TEST_IMAGES_FILE)
                .build();

        MessageResponse messageResponse = mailgunMessagesApi.sendMessage(DOMAIN, message);

Send email (delay example)

        Message message = Message.builder()
                .from(EMAIL_FROM)
                .to(EMAIL_TO)
                .subject(SUBJECT)
                .text(TEXT)
                .deliveryTime(ZonedDateTime.now().plusMinutes(2L)) // Two minutes delay.
                .build();

        MessageResponse messageResponse = mailgunMessagesApi.sendMessage(DOMAIN, message);

Send email (reply-to example)

        Message message = Message.builder()
                .from(EMAIL_FROM)
                .to(EMAIL_TO)
                .subject(SUBJECT)
                .text(TEXT)
                .replyTo(REPLY_TO_EMAIL)
                .build();

        MessageResponse messageResponse = mailgunMessagesApi.sendMessage(DOMAIN, message);

Send email (mailing list example)

        Message message = Message.builder()
                .from(EMAIL_FROM)
                .to(MAILING_LIST_ADDRESS)
                .subject(SUBJECT)
                .text(TEXT)
                .build();

        MessageResponse messageResponse = mailgunMessagesApi.sendMessage(DOMAIN, message);

Send MIME email(s)

Send email(s) in MIME format

        MailgunMimeMessage mailgunMimeMessage = MailgunMimeMessage.builder()
            .to(EMAIL_TO)
            .message(new File("/path/to/file.mime"))
            .build();

        MessageResponse result = mailgunMessagesApi.sendMIMEMessage(MAIN_DOMAIN, mailgunMimeMessage);

More examples - MailgunMessagesIntegrationTest

Store Messages

MailgunStoreMessagesApi allows you to work with stored messages.

Mailgun Store Messages documentation.

Set up MailgunStoreMessagesApi

        MailgunStoreMessagesApi mailgunStoreMessagesApi = MailgunClient.config(storedMessageUrl, PRIVATE_API_KEY)
            .createApiWithAbsoluteUrl(MailgunStoreMessagesApi.class);

Resend email(s)

        MessageResponse result = mailgunStoreMessagesApi.resendMessage(EMAIL_TO);

Retrieve email(s)

        StoreMessageResponse result = mailgunStoreMessagesApi.retrieveMessage();

More examples - MailgunStoreMessagesIntegrationTest

Domains

MailgunDomainsApi allows you to create, access, and validate domains programmatically.

Mailgun Domains documentation.

Set up MailgunDomainsApi

        MailgunDomainsApi mailgunDomainsApi = MailgunClient.config(PRIVATE_API_KEY)
                .createApi(MailgunDomainsApi.class);

Get Domains list

Returns a list of domains under your account (limit to 100 entries).

        DomainListResponse domainListResponse = mailgunDomainsApi.getDomainsList();

Get single Domains

Returns a single domain, including credentials and DNS records. Returns a list of domains under your account with filters.

       SingleDomainResponse singleDomainResponse = mailgunDomainsApi.getSingleDomain(DOMAIN);

Verify Domain

Verifies and returns a single domain, including credentials and DNS records.

If the domain is successfully verified, the domain's state will be active.

       DomainResponse domainResponse = mailgunDomainsApi.verifyDomain(DOMAIN);

For more information on verifying domains, visit Verifying domain documentation

Create Domain

Create a new domain.

       DomainRequest request = DomainRequest.builder()
                .name(DOMAIN_NAME)
                .spamAction(SpamAction.BLOCK)
                .wildcard(true)
                .forceDkimAuthority(false)
                .dkimKeySize(1024)
                .ips(Arrays.asList(IP_1, IP_2))
                .webScheme(WebScheme.HTTPS)
                .build();

        DomainResponse domainResponse = mailgunDomainsApi.createNewDomain(request);

Delete Domain

Delete a domain from your account.

       ResponseWithMessage response = mailgunDomainsApi.deleteDomain(DOMAIN_NAME);

Create credentials

Creates a new set of SMTP credentials for the defined domain.

       DomainCredentials domainCredentials = DomainCredentials.builder()
                .login(LOGIN)
                .password(PASSWORD)
                .build();

        ResponseWithMessage response = mailgunDomainsApi.createNewCredentials(DOMAIN_NAME, domainCredentials);

Update credentials

Updates the specified SMTP credentials.

Currently, only the password can be changed.

       ResponseWithMessage response = mailgunDomainsApi.updateCredentials(DOMAIN_NAME, LOGIN, PASSWORD);

Delete credentials

Deletes the defined SMTP credentials.

       ResponseWithMessage response = mailgunDomainsApi.deleteCredentials(DOMAIN_NAME, LOGIN);

Get connection settings

Returns delivery connection settings for the defined domain.

       DomainConnectionResponse response = mailgunDomainsApi.getDomainConnectionSettings(DOMAIN_NAME);

Update connection settings

Updates the specified delivery connection settings for the defined domain.

        DomainConnectionRequest domainConnection = DomainConnectionRequest.builder()
                .requireTls(false)
                .skipVerification(false)
                .build();

        UpdateDomainConnectionResponse response = mailgunDomainsApi.updateDomainConnectionSettings(DOMAIN_NAME, domainConnection);

Get tracking settings

Returns tracking settings for a domain.

       DomainTrackingResponse response = mailgunDomainsApi.getDomainTrackingSettings(TEST_DOMAIN_NAME);

Update tracking settings

Updates the open tracking settings for a domain.

       UpdateDomainOpenTrackingSettingsResponse response = mailgunDomainsApi.updateDomainOpenTrackingSettings(TEST_DOMAIN_NAME, YesNo.NO);

Update click tracking settings

Updates the click tracking settings for a domain.

       UpdateDomainClickTrackingSettingsResponse response = mailgunDomainsApi.updateDomainClickTrackingSettings(TEST_DOMAIN_NAME, YesNoHtml.HTML_ONLY);

Update unsubscribe tracking settings

Updates unsubscribe tracking settings for a domain.

        DomainUnsubscribeConnectionSettingsRequest request = DomainUnsubscribeConnectionSettingsRequest.builder()
                .active(false)
                .htmlFooter("\n<br>\n<p><a href=\\\"%unsubscribe_url%\\\">unsubscribe java</a></p>\n")
                .textFooter("\n\nTo unsubscribe from java click: <%unsubscribe_url%>\n\n")
                .build();

        UpdateDomainUnsubscribeTrackingSettingsResponse response = mailgunDomainsApi.updateDomainUnsubscribeConnectionSettings(TEST_DOMAIN_NAME, request);

More examples - MailgunDomainsIntegrationTest

IPs

MailgunIPsApi allows you to access information regarding the IPs allocated to your Mailgun account used for outbound sending.

Mailgun IPs documentation.

Set up MailgunIPsApi

        MailgunIPsApi mailgunIPsApi = MailgunClient.config(PRIVATE_API_KEY)
                .createApi(MailgunIPsApi.class);

Get all IPs

Returns a list of IPs assigned to your account.

        IPsResult result = mailgunIPsApi.getAllIPs();

Get dedicated IPs

Return only dedicated IPs if param dedicated set to true, otherwise return all IPs.

        IPsResult result = mailgunIPsApi.getDedicatedIPs(true);

Get specified IP

Returns information about the specified IP.

        IPResult result = mailgunIPsApi.getSpecifiedIP(IP);

Get domain IP

Returns a list of IPs currently assigned to the specified domain.

        IPsResult result = mailgunIPsApi.getDomainIPs(DOMAIN);

Assign IP to domain

Assign a dedicated IP to the domain specified.

Note: Only dedicated IPs can be assigned to a domain.

        ResponseWithMessage response = mailgunIPsApi.assignIPToDomain(DOMAIN, IP);

Unassign IP from domain

Unassign an IP from the domain specified.

        ResponseWithMessage response = mailgunIPsApi.unassignIPFromDomain(DOMAIN, IP);

More examples - MailgunIPsIntegrationTest

Events

MailgunEventsApi Mailgun tracks every event that happens to your emails and makes this data available to you through the Events API.

Mailgun Events documentation.

Set up MailgunEventsApi

        MailgunEventsApi mailgunEventsApi = MailgunClient.config(PRIVATE_API_KEY)
                .createApi(MailgunEventsApi.class);

Get all Events

Get all events that happen to your emails.

        EventsResponse response = mailgunEventsApi.getAllEvents(DOMAIN);

Get specified Events

Get specified events that happen to your emails.

        EventsQueryOptions eventsQueryOptions = EventsQueryOptions.builder()
                .event(EventType.DELIVERED)
                .build();

        EventsResponse response = mailgunEventsApi.getEvents(DOMAIN, eventsQueryOptions);

Get Events next page

Fetches the next page of log records, assuming that the previous request returned the pageId.

        EventsResponse response = mailgunEventsApi.getEvents(DOMAIN, pageId);

More examples - MailgunEventsIntegrationTest

Stats

MailgunStatisticsApi Mailgun collects many different events and generates event statistics available via this API.

Mailgun Statistics documentation.

Set up MailgunStatisticsApi

        MailgunStatisticsApi mailgunStatisticsApi = MailgunClient.config(PRIVATE_API_KEY)
                .createApi(MailgunStatisticsApi.class);

Get domain Statistics

Returns total statistics for a given domain.

        StatisticsOptions statsOptions = StatisticsOptions.builder()
                .start(ZonedDateTime.now().minusDays(3))
                .end(ZonedDateTime.now())
                .event(Arrays.asList(StatsEventType.ACCEPTED, StatsEventType.DELIVERED))
                .build();

        StatsResult result = mailgunStatisticsApi.getDomainStats(DOMAIN, statsOptions);

More examples - MailgunStatisticsIntegrationTest

Tags

MailgunTagsApi Mailgun lets you tag each outgoing message with a custom value and provides statistics on the tag level.

Mailgun Tags documentation.

Set up MailgunTagsApi

        MailgunTagsApi mailgunTagsApi = MailgunClient.config(PRIVATE_API_KEY)
                .createApi(MailgunTagsApi.class);

Get all Tags

Returns a list of tags for a domain.

        TagsResult result = mailgunTagsApi.getAllTags(DOMAIN);

Get Tag

Returns a given tag.

        TagsItem result = mailgunTagsApi.getTag(DOMAIN, TAG);

Update Tag

Updates a given tag with the information provided.

        TagUpdateRequest request = TagUpdateRequest.builder()
                .description(newDescription)
                .build();

        ResponseWithMessage response = mailgunTagsApi.updateTag(DOMAIN, TAG, request);

Get Tag statistics

Returns statistics for a given tag.

        StatisticsOptions statisticsOptions = StatisticsOptions.builder()
                .event(Arrays.asList(StatsEventType.ACCEPTED, StatsEventType.DELIVERED))
                .resolution(ResolutionPeriod.DAY)
                .duration(3, Duration.DAY)
                .build();

        TagStatsResult result = mailgunTagsApi.getTagStatistics(DOMAIN, TAG, statisticsOptions);

Delete Tag

Deletes the tag.

        ResponseWithMessage response = mailgunTagsApi.deleteTag(DOMAIN, TAG);

List Tag countries

Returns a list of countries of origin for a given domain for different event types.

        TagCountriesResponse response = mailgunTagsApi.listTagCountries(DOMAIN, TAG);

List Tag providers

Returns a list of email providers for a given domain for different event types.

        TagProvidersResponse response = mailgunTagsApi.listTagProviders(DOMAIN, TAG);

List Tag devices

Returns a list of devices for a given domain that have triggered event types.

        TagDevicesResponse response = mailgunTagsApi.listTagDevices(DOMAIN, TAG);

More examples - MailgunTagsApiIntegrationTest

Suppressions

Mailgun Suppressions documentation.

Suppression Bounces

MailgunSuppressionBouncesApi

Mailgun Suppression Bounces documentation.

Set up MailgunSuppressionBouncesApi

        MailgunSuppressionBouncesApi mailgunSuppressionBouncesApi = MailgunClient.config(PRIVATE_API_KEY)
                .createApi(MailgunSuppressionBouncesApi.class);

Get Bounces

Returns a list of bounces for a domain.

        BouncesResponse response = suppressionBouncesApi.getBounces(DOMAIN, MAXIMUM_NUMBER_OF_RECORDS);

Get Bounce

Fetch a single bounce event by a given email address.

Helpful to check if a given email address has bounced before.

        BouncesItem response = suppressionBouncesApi.getBounce(DOMAIN, ADDRESS);

Add Bounce

Add a single bounce record to the bounce list.

Updates the existing record if the address is already there.

        BouncesRequest bouncesRequest = BouncesRequest.builder()
                .address(ADDRESS)
                .code(CODE)
                .error(ERROR_MESSAGE)
                .createdAt(DATE_TIME)
                .build();

        SuppressionResponse response = suppressionBouncesApi.addBounce(DOMAIN, bouncesRequest);

Add Bounces

Add multiple bounce records to the bounce list in a single API call.

        BouncesRequest bouncesRequest1 = BouncesRequest.builder()
                .address(ADDRESS_1)
                .code(CODE)
                .error(ERROR_MESSAGE)
                .createdAt(DATE_TIME)
                .build();

        BouncesRequest bouncesRequest2 = BouncesRequest.builder()
                .address(ADDRESS_2)
                .code(CODE)
                .error(ERROR_MESSAGE)
                .createdAt(DATE_TIME)
                .build();

        ResponseWithMessage response = suppressionBouncesApi.addBounces(DOMAIN, Arrays.asList(bouncesRequest1, bouncesRequest2));

Import Bounces

Import a list of bounces.

        BouncesListImportRequest request = BouncesListImportRequest.builder()
            .file(new File("/path/to/file"))
            .build();

        ResponseWithMessage result = suppressionBouncesApi.importBounceList(MAIN_DOMAIN, request);

Delete Bounce

Delete a single bounce.

        ResponseWithMessage response = suppressionBouncesApi.deleteBounce(DOMAIN, ADDRESS);

Delete all Bounces

Delete all bounced email addresses for a domain.

        ResponseWithMessage response = suppressionBouncesApi.deleteAllBounces(DOMAIN);

More examples - MailgunSuppressionBouncesApiIntegrationTest

Suppression Complaints

MailgunSuppressionComplaintsApi

Mailgun Suppression Complaints documentation.

Set up MailgunSuppressionComplaintsApi

        MailgunSuppressionComplaintsApi mailgunSuppressionComplaintsApi = MailgunClient.config(PRIVATE_API_KEY)
                .createApi(MailgunSuppressionComplaintsApi.class);

Get all Complaints

Returns a list of complaints for a domain.

        ComplaintsItemResponse response = suppressionComplaintsApi.getAllComplaints(DOMAIN, MAXIMUM_NUMBER_OF_RECORDS);

Get single Complaint

Fetch a single spam complaint by a given email address.

Helpful to check if a particular user has complained.

        ComplaintsItem response = suppressionComplaintsApi.getSingleComplaint(DOMAIN, EMAIL);

Add Address

Add an address to the complaints list.

        ComplaintsSingleItemRequest request = ComplaintsSingleItemRequest.builder()
                .address(EMAIL)
                .createdAt(DATE_TIME)
                .build();

        SuppressionResponse response = suppressionComplaintsApi.addAddressToComplaintsList(DOMAIN, request);

Add Addresses

Add multiple complaint records to the complaint list in a single API call(up to 1000 complaint records).

        ComplaintsItem complaintsItem1 = ComplaintsItem.builder()
                .address(EMAIL_1)
                .createdAt(DATE_TIME)
                .build();

        ComplaintsItem complaintsItem2 = ComplaintsItem.builder()
                .address(EMAIL_2)
                .build();

        ResponseWithMessage response = suppressionComplaintsApi.addAddressesToComplaintsList(MAIN_DOMAIN, Arrays.asList(complaintsItem1, complaintsItem2));

Import Addresses

Import a list of complaints.

        ComplaintsListImportRequest request = ComplaintsListImportRequest.builder()
            .file(new File("/path/to/file"))
            .build();

        ResponseWithMessage result = suppressionComplaintsApi.importComplaintsList(MAIN_DOMAIN, request);

Remove Address

Remove Address From Complaints.

        SuppressionResponse response = suppressionComplaintsApi.removeAddressFromComplaints(DOMAIN, EMAIL);

More examples - MailgunSuppressionComplaintsApiIntegrationTest

Suppression Unsubscribe

MailgunSuppressionUnsubscribeApi

Mailgun Suppression Unsubscribe documentation.

Set up MailgunSuppressionUnsubscribeApi

        MailgunSuppressionUnsubscribeApi mailgunSuppressionUnsubscribeApi = MailgunClient.config(PRIVATE_API_KEY)
                .createApi(MailgunSuppressionUnsubscribeApi.class);

Get all Unsubscribe

Returns a list of unsubscribes for a domain.

        UnsubscribeItemResponse response = suppressionUnsubscribeApi.getAllUnsubscribe(DOMAIN, MAXIMUM_NUMBER_OF_RECORDS);

Get single Unsubscribe

Fetch a single unsubscribe record.

Can be used to check if a given address is present in the list of unsubscribed users.

        UnsubscribeItem response = suppressionUnsubscribeApi.getSingleUnsubscribe(DOMAIN, EMAIL);

Add address

Add an address to the unsubscribe table.

        UnsubscribeSingleItemRequest request = UnsubscribeSingleItemRequest.builder()
                .address(EMAIL)
                .tag(TAG)
                .createdAt(DATE_TIME)
                .build();

        SuppressionResponse response = suppressionUnsubscribeApi.addAddressToUnsubscribeTable(DOMAIN, request);

Add addresses

Add multiple unsubscribe records to the unsubscribe list in a single API call(up to 1000 unsubscribe records).

        UnsubscribeItem unsubscribeItemAllFields = UnsubscribeItem.builder()
        .address(EMAIL_1)
        .tags(Arrays.asList(TAG_1, TAG_2))
        .createdAt(DATE_TIME)
        .build();

        UnsubscribeItem unsubscribeItemAddressOnly = UnsubscribeItem.builder()
        .address(EMAIL_2)
        .build();

        ResponseWithMessage response = suppressionUnsubscribeApi.addAddressesToUnsubscribeTable(DOMAIN, Arrays.asList(unsubscribeItemAllFields, unsubscribeItemAddressOnly));

Import addresses

Import a CSV file containing a list of addresses to add to the unsubscribe list.

        UnsubscribesListImportRequest request = UnsubscribesListImportRequest.builder()
        .file(new File("/path/to/file"))
        .build();

        ResponseWithMessage result = suppressionUnsubscribeApi.importAddressesToUnsubscribeTable(MAIN_DOMAIN, request);

Remove address tag

Remove an address from the unsubscribes list.

        SuppressionResponse response = suppressionUnsubscribeApi.removeAddressFromUnsubscribeTag(DOMAIN, EMAIL, TAG);

Remove address

Completely remove an address from the unsubscribes list.

        SuppressionResponse response = suppressionUnsubscribeApi.removeAddressFromUnsubscribeList(DOMAIN, EMAIL);

More examples - MailgunSuppressionUnsubscribeApiIntegrationTest

Suppression Whitelists

MailgunSuppressionWhitelistsApi

Mailgun Suppression Whitelists documentation.

Set up MailgunSuppressionWhitelistsApi

        MailgunSuppressionWhitelistsApi mailgunSuppressionWhitelistsApi = MailgunClient.config(PRIVATE_API_KEY)
                .createApi(MailgunSuppressionWhitelistsApi.class);

Get all Whitelists

Returns a list of whitelists for a domain.

        WhitelistsItemResponse response = suppressionWhitelistsApi.getAllWhitelists(DOMAIN, MAXIMUM_NUMBER_OF_RECORDS);

Get single Whitelist

Fetch a single whitelist record.

Can be used to check if a given address or domain is present in the whitelist table.

        WhitelistsItem response = suppressionWhitelistsApi.getSingleWhitelistRecord(DOMAIN, EMAIL);

Add address/domain

Add an address or domain to the whitelist table.

Note: The single request accepts either one address or domain parameter.

        WhitelistsRequest request = WhitelistsRequest.builder()
                .address(EMAIL)
                .reason(REASON)
                .build();

        ResponseWithMessage response = suppressionWhitelistsApi.addSingleWhitelistRecord(DOMAIN, request);

Import address/domain

Import a CSV file containing a list of addresses and/or domains to add to the whitelist.

        WhitelistsListImportRequest request = WhitelistsListImportRequest.builder()
        .file(new File("/path/to/file"))
            .build();

        ResponseWithMessage result = suppressionWhitelistsApi.importWhitelistRecords(MAIN_DOMAIN, request);

Delete address/domain

Delete a single record from whitelist table.

        WhitelistsRemoveRecordResponse response = suppressionWhitelistsApi.removeRecordFromWhitelists(DOMAIN, EMAIL);

More examples - MailgunSuppressionWhitelistsApiIntegrationTest

Routes

MailgunRoutesApi allows you to work with routes programmatically.

Mailgun Routes documentation.

Set up MailgunRoutesApi

        MailgunRoutesApi mailgunRoutesApi = MailgunClient.config(PRIVATE_API_KEY)
                .createApi(MailgunRoutesApi.class);

Get Routes list

Fetches the list of routes.

        RoutesPageRequest pageRequest = RoutesPageRequest.builder()
                .limit(2)
                .skip(2)
                .build();

        RoutesListResponse response = mailgunRoutesApi.getRoutesList(pageRequest);

Get single Route

Returns a single route object based on its ID.

        SingleRouteResponse response = mailgunRoutesApi.getSingleRoute(ROUTE_ID);

Create Route

Creates a new route.

        RoutesRequest routesRequest = RoutesRequest.builder()
                .priority(2)
                .description(DESCRIPTION)
                .expression("match_recipient('.*some-address-@example.com')")
                .action("forward('" + EMAIL_2 + "')")
                .action("forward('" + EMAIL_3 + "')")
                .actions(Arrays.asList("forward('https://myhost.com/messages')", "stop()"))
                .build();

        RoutesResponse response = mailgunRoutesApi.createRoute(routesRequest);

Update Route

Updates a given route by ID.

        RoutesRequest routesRequest = RoutesRequest.builder()
                .priority(1)
                .action("forward('" + EMAIL + "')")
                .build();

        Route result = mailgunRoutesApi.updateRoute(routeId, routesRequest);

Delete Route

Deletes a route based on the id.

        ResponseWithMessage response = mailgunRoutesApi.deleteRoute(ROUTE_ID);

More examples - MailgunRoutesIntegrationTest

Webhooks

MailgunWebhooksApi allows you to create, access, and delete webhooks programmatically.

Mailgun Webhooks documentation.

Set up MailgunWebhooksApi

        MailgunWebhooksApi mailgunWebhooksApi = MailgunClient.config(PRIVATE_API_KEY)
                .createApi(MailgunWebhooksApi.class);

Get all Webhooks

Returns a list of webhooks set for the specified domain.

        WebhookListResult result = mailgunWebhooksApi.getAllWebhooks(DOMAIN);

Get Webhooks details

Return details about a webhook specified in the URL.

        WebhookDetailsResult result = mailgunWebhooksApi.getWebhookDetails(DOMAIN, WebhookName.CLICKED);

Create Webhook

Creates a new webhook.

        WebhookRequest request = WebhookRequest.builder()
                .webhookName(WebhookName.CLICKED)
                .url(WEBHOOK_URL)
                .build();

        WebhookResult result = mailgunWebhooksApi.createNewWebhook(DOMAIN, request);

Update Webhook

Updates an existing webhook.

        WebhookUpdateRequest request = WebhookUpdateRequest.builder()
                .urls(Arrays.asList(WEBHOOK_URL_2, WEBHOOK_URL_3))
                .build();

        WebhookResult result = mailgunWebhooksApi.updateWebhook(MAIN_DOMAIN, WebhookName.CLICKED, request);

Delete Webhook

Deletes an existing webhook.

        WebhookResult result = mailgunWebhooksApi.deleteWebhook(DOMAIN, WebhookName.CLICKED);

More examples - MailgunWebhooksApiIntegrationTest

Mailing Lists

You can programmatically create mailing lists using MailgunMailingListApi

Mailgun Mailing Lists documentation.

Set up MailgunMailingListApi

        MailgunMailingListApi mailgunMailingListApi = MailgunClient.config(PRIVATE_API_KEY)
                .createApi(MailgunMailingListApi.class);

Get Mailing List

Returns mailing lists under your account.

        MailingListDataResponse response = mailgunMailingListApi.getMailingList(MAXIMUM_NUMBER_OF_RECORDS);

Get Mailing List by address

Returns a single mailing list by a given address.

        SingleMailingListResponse response = mailgunMailingListApi.getMailingListByAddress(ADDRESS);

Create Mailing List

Creates a new mailing list.

        MailingListRequest request = MailingListRequest.builder()
                .address(MAILING_LIST_ADDRESS)
                .name(MAILING_LIST_NAME)
                .description(DESCRIPTION)
                .accessLevel(AccessLevel.EVERYONE)
                .replyPreference(ReplyPreference.LIST)
                .build();

        MailingListResponse response = mailgunMailingListApi.createMailingList(request);

Update Mailing List

Update mailing list properties, such as address, description or name.

        UpdateMailingListRequest request = UpdateMailingListRequest.builder()
                .address(NEW_ADDRESS)
                .name(NEW_MAILING_LIST_NAME)
                .description(NEW_DESCRIPTION)
                .accessLevel(AccessLevel.MEMBERS)
                .replyPreference(ReplyPreference.SENDER)
                .build();

        MailingListResponse response = mailgunMailingListApi.updateMailingList(MAILING_LIST_ADDRESS, request);

Delete Mailing List

Deletes a mailing list.

        DeleteMailingListResponse response = mailgunMailingListApi.deleteMailingList(MAILING_LIST_ADDRESS);

Verify Mailing List members

Verify all the members of the mailing list.

        MailingListVerificationResponse response = mailgunMailingListApi.verifyMailingListMembers(MAILING_LIST_ADDRESS);

Verification job status

Retrieve the current status of the mailing list verification job.

        MailingListVerificationStatusResponse response = mailgunMailingListApi.getMailingListVerificationJobStatus(MAILING_LIST_ADDRESS);

Cancel verification job

Cancel an active mailing list verification job.

        String result = mailgunMailingListApi.cancelActiveMailingListVerificationJob(MAILING_LIST_ADDRESS);

List of members

Returns the list of members in the given mailing list.

        MailingListMembersRequest request = MailingListMembersRequest.builder()
            .limit(10)
            .build();

        MailingListMembersResponse response = mailgunMailingListApi.getMailingListMembers(MAILING_LIST_ADDRESS, request);

Mailing List member

Retrieves a mailing list member.

        MailingListMemberResponse response = mailgunMailingListApi.getMailingListMember(MAILING_LIST_ADDRESS, MEMBER_EMAIL);

Add member

Adds a member to the mailing list.

        MailingListNewMemberRequest request = MailingListNewMemberRequest.builder()
                .address(MEMBER_EMAIL)
                .name(MEMBER_NAME)
                .vars(MAP_OF_PARAMETERS)
                .subscribed(true)
                .build();

        MailingListMemberResponse response = mailgunMailingListApi.addMemberToMailingList(MAILING_LIST_ADDRESS, request);

Update member

Updates a mailing list member with given properties. Won't touch the property if it's not passed in.

        MailingListMemberUpdateRequest request = MailingListMemberUpdateRequest.builder()
                .name(NEW_NAME)
                .vars(MAP_OF_PARAMETERS)
                .subscribed(true)
                .build();

        MailingListMemberResponse response = mailgunMailingListApi.updateMailingListMember(MAILING_LIST_ADDRESS, MEMBER_EMAIL, request);

Add members

Adds multiple members, up to 1,000 per call, to a Mailing List.

        MailingListMember mailingListMember_1 = MailingListMember.builder()
                .address(MEMBER_1_EMAIL)
                .name(MEMBER_NAME)
                .vars(MAP_OF_PARAMETERS)
                .subscribed(true)
                .build();

        MailingListMember mailingListMember_2 = MailingListMember.builder()
                .address(MEMBER_2_EMAIL)
                .name(MEMBER_NAME)
                .vars(MAP_OF_PARAMETERS)
                .subscribed(false)
                .build();

        AddMailingListMembersRequest request = AddMailingListMembersRequest.builder()
                .members(Arrays.asList(mailingListMember_1, mailingListMember_2))
                .upsert(true)
                .build();

        MailingListResponse response = mailgunMailingListApi.addMembersToMailingList(MAILING_LIST_ADDRESS, request);

Delete member

Delete a mailing list member.

        MailingListMemberResponse response = mailgunMailingListApi.deleteMemberFromMailingList(MAILING_LIST_ADDRESS, MEMBER_EMAIL);

More examples - MailgunMailingListApiIntegrationTest

Templates

MailgunTemplatesApi allows you to access information regarding the IPs allocated to your Mailgun account that is used for outbound sending.

Mailgun Templates documentation.

Set up MailgunTemplatesApi

        MailgunTemplatesApi mailgunTemplatesApi = MailgunClient.config(PRIVATE_API_KEY)
                .createApi(MailgunTemplatesApi.class);

Get all Templates

Returns a list of stored templates for the domain (limit to 10 entries).

        TemplatesResult result = mailgunTemplatesApi.getAllTemplates(DOMAIN);

Get all Templates(paging)

Returns a list of stored templates for the domain with paging.

        PagingWithPivot pagingWithPivot = PagingWithPivot.builder()
                .limit(2)
                .page(Page.NEXT)
                .pivot(TEMPLATE_NAME)
                .build();

        TemplatesResult result = mailgunTemplatesApi.getAllTemplates(MAIN_DOMAIN, pagingWithPivot);

Get Template

Returns metadata information about a stored template.

        TemplateResponse response = mailgunTemplatesApi.getTemplate(DOMAIN, TEMPLATE_NAME);

Get Template Content

Returns the content of the active version of the template with metadata information.

        TemplateWithVersionResponse response = mailgunTemplatesApi.getActiveTemplateVersionContent(DOMAIN, TEMPLATE_NAME);

Create Template

This API stores a new template, including its name, description, and (optionally) the template content.

If the template content is provided, a new version is automatically created and becomes the active version.

        TemplateRequest request = TemplateRequest.builder()
                .name(TEMPLATE_NAME)
                .description(TEMPLATE_DESCRIPTION)
                .template("Hey, {{name}}!")
                .tag(TEMPLATE_VERSION_TAG)
                .engine(TEMPLATE_ENGINE)
                .comment(TEMPLATE_COMMENT)
                .build();

        TemplateWithMessageResponse response = mailgunTemplatesApi.storeNewTemplate(DOMAIN, request);

Update Template

Update the metadata information of the template.

        TemplateStatusResponse response = mailgunTemplatesApi.updateTemplate(DOMAIN, TEMPLATE_NAME, TEMPLATE_DESCRIPTION);

Delete Template

Delete the template.

        TemplateStatusResponse response = mailgunTemplatesApi.deleteTemplate(DOMAIN, TEMPLATE_NAME);

Delete all Templates

Delete all stored templates for the domain.

        ResponseWithMessage response = mailgunTemplatesApi.deleteAllTemplatesInDomain(DOMAIN);

List Template stored versions

Returns a list of stored versions of the template.

        TemplateAllVersionsResponse response = mailgunTemplatesApi.getAllTemplateVersions(DOMAIN, TEMPLATE_NAME);

Get specified version Template Content

Retrieve information and content of specified version of the template.

        TemplateWithVersionResponse response = mailgunTemplatesApi.getSpecifiedVersionTemplateContent(DOMAIN, TEMPLATE_NAME, TEMPLATE_VERSION_TAG);

Create new Template version

Create a new version of a template.

If the template does not contain any other versions, the first version becomes active.

        TemplateVersionRequest request = TemplateVersionRequest.builder()
                .template(TEMPLATE)
                .tag(TEMPLATE_VERSION_TAG)
                .engine(TEMPLATE_ENGINE)
                .comment(TEMPLATE_COMMENT)
                .active(true)
                .build();

        TemplateWithMessageResponse response = mailgunTemplatesApi.createNewTemplateVersion(DOMAIN, TEMPLATE_NAME, request);

Update Template version

Update information or content of the specific version of the template.

        UpdateTemplateVersionRequest request = UpdateTemplateVersionRequest.builder()
                .template(TEMPLATE)
                .comment(TEMPLATE_COMMENT)
                .active(true)
                .build();

        TemplateVersionResponse response = mailgunTemplatesApi.updateSpecificTemplateVersion(DOMAIN, TEMPLATE_NAME, TEMPLATE_VERSION_TAG, request);

Delete Template version

Delete a specific version of the template.

        TemplateVersionResponse response = mailgunTemplatesApi.deleteSpecificTemplateVersion(DOMAIN, TEMPLATE_NAME, TEMPLATE_VERSION_TAG);

More examples - MailgunTemplatesIntegrationTest

Email Validation/Verification

MailgunEmailVerificationApi is an email address verification service.

Mailgun Email Validation/Verification documentation.

Set up MailgunEmailVerificationApi

        MailgunEmailVerificationApi mailgunEmailVerificationApi = MailgunClient.config(PRIVATE_API_KEY)
                .createApi(MailgunEmailVerificationApi.class);

Validate address

Given an arbitrary address, validates address based on defined checks.

        AddressValidationResponse result = mailgunEmailVerificationApi.validateAddress(EMAIL);

Get verification job list

Get list of all bulk verification jobs.

        BulkVerificationJobListResponse result = mailgunEmailVerificationApi.getBulkVerificationJobList();

Get verification job status

Check the current status of a bulk verification job.

        BulkVerificationJobStatusResponse result = mailgunEmailVerificationApi.getBulkVerificationJobStatus(LIST_NAME);

Create verification job

Create a bulk verification job.

        BulkVerificationStatusRequest request = BulkVerificationStatusRequest.builder()
            .file(new File("/path/to/file"))
            .build();

        BulkVerificationCreatingResponse result = mailgunEmailVerificationApi.createBulkVerificationJob(LIST_NAME, request);

Cancel verification job

Cancel current running bulk verification job.

        String result = mailgunEmailVerificationApi.cancelBulkVerificationJob(LIST_NAME);

Get preview list

Get list of all bulk verification previews.

        BulkVerificationPreviewListResponse result = mailgunEmailVerificationApi.getBulkVerificationPreviewList();

Check preview status

Check the current status of a bulk verification preview.

        BulkVerificationPreviewResponse result = mailgunEmailVerificationApi.getBulkVerificationPreviewStatus(LIST_NAME);

Create verification preview

Create a bulk verification preview.

        BulkVerificationStatusRequest request = BulkVerificationStatusRequest.builder()
            .file(new File("/path/to/file"))
            .build();

        BulkVerificationCreatingResponse result = mailgunEmailVerificationApi.createBulkVerificationPreview(LIST_NAME, request);

Delete verification preview

Delete a bulk verification preview.

        Response result = mailgunEmailVerificationApi.deleteBulkVerificationPreview(LIST_NAME);

More examples - MailgunEmailVerificationIntegrationTest

Inbox Placement

MailgunSeedListApi A seed list is an object that provides the mailing list for your inbox placement test. It also acts as a container for all the results of those tests and will aggregate the stats of all the tests..

Inbox Placement documentation.

Set up MailgunSeedListApi

        MailgunSeedListApi mailgunSeedListApi = MailgunClient.config(PRIVATE_API_KEY)
                .createApi(MailgunSeedListApi.class);

Generate seed list

Generate a seed list

        SeedListRequest request = SeedListRequest.builder()
            .seedFilter(SEED_FILTER)
            .name(SEED_LIST_NAME)
            .sendingDomains(Arrays.asList(TEST_DOMAIN_1, TEST_DOMAIN_2))
            .build();

        SeedListItem result = mailgunSeedListApi.generateSeedList(request);

Update seed list

You can update a seed list with this endpoint.

        SeedListRequest request = SeedListRequest.builder()
            .seedFilter(SEED_FILTER)
            .name(SEED_LIST_NAME)
            .sendingDomains(Arrays.asList(TEST_DOMAIN_1, TEST_DOMAIN_2))
            .build();

        SeedListItem result = mailgunSeedListApi.updateSeedList(TARGET_EMAIL, request);

Get seed lists

Get a list of all of your seed lists. You can filter this using the available filters.

        SeedListsPageRequest filter = SeedListsPageRequest.builder()
            .limit(2)
            .offset(1)
            .ascending(false)
            .build();

        SeedListsResponse result = mailgunSeedListApi.getAllSeedLists(filter);

Get seed list

You can select a single seed list with this endpoint.

        SingleSeedListResponse result = mailgunSeedListApi.getSeedList(TARGET_EMAIL);

Get seed list attributes

Get all iterable attributes of seed lists.

        SeedListsAttributesResponse result = mailgunSeedListApi.getSeedListsAttributes();

Get seed list attribute

Get all values of a specific attribute of your seed lists.

        SeedListsAttributesResponse result = mailgunSeedListApi.getSeedListsAttribute(ATTRIBUTE_NAME);

Get seed list filters

Get all available filters for seed lists.

        SeedListsFiltersResponse result = mailgunSeedListApi.getSeedListFilters();

Delete seed list

Delete a seed list.

        Response result = mailgunSeedListApi.deleteSeedListFeignResponse(TARGET_EMAIL);

Get list results

Test results are generated when a message has been received at the target_email.

        Response result = mailgunSeedListApi.getResultsFeignResponse();

Get results filters

Get Available Result Filters.

        Response result = mailgunSeedListApi.getAvailableResultFiltersFeignResponse();

Get results attributes

Get all iterable attributes of results.

        SeedListsAttributesResponse result = mailgunSeedListApi.getResultsAttributes();

Get results attribute

Get all values of a specific attribute of your results lists.

        SeedListsAttributesResponse result = mailgunSeedListApi.getResultsAttribute(ATTRIBUTE);

Get specific result

Get a specific result.

        Response result = mailgunSeedListApi.getSpecificResultFeignResponse(RID);

Delete result

Delete a result.

        Response result = mailgunSeedListApi.deleteResultFeignResponse(RID);

More examples - MailgunSeedListIntegrationTest

Testing

WARNING - running the tests will cost you money!

To run the tests, various environment variables must be set:

  • PRIVATE_API_KEY To view your primary account API key in the Mailgun dashboard, click on Settings on the left-hand nav in the Mailgun dashboard and then API Keys and click on the eye icon next to API_KEYS.
  • MAIN_DOMAIN is the domain name - this is a value registered in the Mailgun admin interface or using MailgunDomainsApi.class.
  • EMAIL_FROM is the email address used in various sending tests.
  • EMAIL_TO is the email address used in various sending tests.

Run tests, including integration tests:

        mvn verify -Pintegration-test

Run tests, excluding integration tests:

        mvn verify

Contribute

Mailgun loves developers. You can be part of this project!

Feel free to ask anything, and contribute:

  • Fork the project.
  • Create a new branch.
  • Implement your feature or bug fix.
  • Add documentation for it.
  • Add specs for your feature or bug fix.
  • Commit and push your changes.
  • Submit a pull request.

If you have suggestions on improving the guides, please submit an issue in our Official API Documentation repo.