The Mailgun Java SDK enables Java developers to work with Mailgun API efficiently.
Changes to the SDK beginning with version 1.0.1 (June 2022) are tracked in CHANGELOG.md.
To run the SDK, you will need Java 1.8+.
The recommended way to use the Mailgun Java SDK in your project:
Maven.
Add the following to your pom.xml
:
<dependencies>
...
<dependency>
<groupId>com.mailgun</groupId>
<artifactId>mailgun-java</artifactId>
<version>1.1.3</version>
</dependency>
...
</dependencies>
Gradle Groovy DSL .
implementation 'com.mailgun:mailgun-java:1.1.3'
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.
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/
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);
// For US servers
MailgunClient.config(PRIVATE_API_KEY)
// For EU servers
MailgunClient.config(EU_BASE_URL, PRIVATE_API_KEY)
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))
You can add your multiple custom:
- request header in format:
(headerName, headerValue)
- form property with allowed prefixes such as:
t:, o:, h:, v:
with the followed by any arbitrary value.
MailgunMessagesApi mailgunMessagesApi = MailgunClient.config(API_KEY)
.createApiWithRequestInterceptor(MailgunMessagesApi.class,
MailgunRequestInterceptor.builder()
.addHeader(HEADER_ON_BEHALF_OF, SUBACCOUNT_ACCOUNT_ID)
.addProperty("h:X-My-Header", "my_custom_header")
.build()
);
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);
@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
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:
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);
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
- Messages
- Set up MailgunMessagesApi
- Send email
- Send email(name with email)
- Send emails
- Async send email(s)
- Send email (html example)
- Send email (attachments example)
- Send email (attachment FormData example)
- Send email (inline multiple files example)
- Send email (delay example)
- Send email (reply-to example)
- Send email (mailing list example)
- Send email (sender example)
- Send email (with custom form property)
- Send email(s) in MIME format
- Store Messages
- Domains
- Set up MailgunDomainsApi
- Get Domains list
- Get single Domains
- Verify Domain
- Create Domain
- Delete Domain
- Create credentials
- Update credentials
- Get connection settings
- Update connection settings
- Get tracking settings
- Update tracking settings
- Update click tracking settings
- Update unsubscribe tracking settings
- IPs
- Events
- Stats
- Tags
- Suppressions
- Routes
- Webhooks
- Mailing Lists
- Templates
- Set up MailgunTemplatesApi
- Get all Templates
- Get all Templates(paging)
- Get Template
- Get Template Content
- Create Template
- Update Template
- Delete Template
- Delete all Templates
- List Template stored versions
- Get specified version Template Content
- Create new Template version
- Update Template version
- Delete Template version
- Email Validation/Verification
- [Inbox Placement](#Inbox Placement)
- Messages
MailgunMessagesApi allows you to send emails.
Mailgun Messages documentation.
When you submit messages for delivery, Mailgun places them in a message queue.
MailgunMessagesApi mailgunMessagesApi = MailgunClient.config(PRIVATE_API_KEY)
.createApi(MailgunMessagesApi.class);
Message message = Message.builder()
.from(EMAIL_FROM)
.to(USER_EMAIL)
.subject(SUBJECT)
.text(TEXT)
.build();
MessageResponse messageResponse = mailgunMessagesApi.sendMessage(DOMAIN, message);
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);
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);
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);
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);
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);
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);
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);
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);
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);
Message message = Message.builder()
.from(EMAIL_FROM)
.to(MAILING_LIST_ADDRESS)
.subject(SUBJECT)
.text(TEXT)
.build();
MessageResponse messageResponse = mailgunMessagesApi.sendMessage(DOMAIN, message);
Message message = Message.builder()
.from(EMAIL_FROM)
.to(EMAIL_TO)
.sender(SENDER_EMAIL)
.subject(SUBJECT)
.text(TEXT)
.build();
MessageResponse messageResponse = mailgunMessagesApi.sendMessage(DOMAIN, message);
or sender with name and email
Message message = Message.builder()
.from(EMAIL_FROM)
.to(EMAIL_TO)
.sender(EmailUtil.nameWithEmail(SENDER_NAME, SENDER_EMAIL))
.subject(SUBJECT)
.text(TEXT)
.build();
MessageResponse messageResponse = mailgunMessagesApi.sendMessage(DOMAIN, message);
You can send email(s) with your own custom dynamic form property with allowed prefixes such as: t:, o:, h:, v:
with the followed by any arbitrary value.
MailgunMessagesApi mailgunMessagesApi = MailgunClient.config(PRIVATE_API_KEY)
.createApiWithRequestInterceptor(MailgunMessagesApi.class,
MailgunRequestInterceptor.builder()
.addProperty("h:Sender", EmailUtil.nameWithEmail(SENDER_NAME, SENDER_EMAIL))
.addProperty("h:X-My-Header", "my_custom_header")
.build()
);
Message message = Message.builder()
.from(EMAIL_FROM)
.to(EMAIL_TO)
.subject(SUBJECT)
.text(TEXT)
.build();
MessageResponse messageResponse = mailgunMessagesApi.sendMessage(DOMAIN, message);
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
MailgunStoreMessagesApi allows you to work with stored messages.
Mailgun Store Messages documentation.
MailgunStoreMessagesApi mailgunStoreMessagesApi = MailgunClient.config(storedMessageUrl, PRIVATE_API_KEY)
.createApiWithAbsoluteUrl(MailgunStoreMessagesApi.class);
MessageResponse result = mailgunStoreMessagesApi.resendMessage(EMAIL_TO);
StoreMessageResponse result = mailgunStoreMessagesApi.retrieveMessage();
More examples - MailgunStoreMessagesIntegrationTest
MailgunDomainsApi allows you to create, access, and validate domains programmatically.
Mailgun Domains documentation.
MailgunDomainsApi mailgunDomainsApi = MailgunClient.config(PRIVATE_API_KEY)
.createApi(MailgunDomainsApi.class);
Returns a list of domains under your account (limit to 100 entries).
DomainListResponse domainListResponse = mailgunDomainsApi.getDomainsList();
Returns a single domain, including credentials and DNS records. Returns a list of domains under your account with filters.
SingleDomainResponse singleDomainResponse = mailgunDomainsApi.getSingleDomain(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 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 a domain from your account.
ResponseWithMessage response = mailgunDomainsApi.deleteDomain(DOMAIN_NAME);
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);
Updates the specified SMTP credentials.
Currently, only the password can be changed.
ResponseWithMessage response = mailgunDomainsApi.updateCredentials(DOMAIN_NAME, LOGIN, PASSWORD);
Deletes the defined SMTP credentials.
ResponseWithMessage response = mailgunDomainsApi.deleteCredentials(DOMAIN_NAME, LOGIN);
Returns delivery connection settings for the defined domain.
DomainConnectionResponse response = mailgunDomainsApi.getDomainConnectionSettings(DOMAIN_NAME);
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);
Returns tracking settings for a domain.
DomainTrackingResponse response = mailgunDomainsApi.getDomainTrackingSettings(TEST_DOMAIN_NAME);
Updates the open tracking settings for a domain.
UpdateDomainOpenTrackingSettingsResponse response = mailgunDomainsApi.updateDomainOpenTrackingSettings(TEST_DOMAIN_NAME, YesNo.NO);
Updates the click tracking settings for a domain.
UpdateDomainClickTrackingSettingsResponse response = mailgunDomainsApi.updateDomainClickTrackingSettings(TEST_DOMAIN_NAME, YesNoHtml.HTML_ONLY);
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
MailgunIPsApi allows you to access information regarding the IPs allocated to your Mailgun account used for outbound sending.
MailgunIPsApi mailgunIPsApi = MailgunClient.config(PRIVATE_API_KEY)
.createApi(MailgunIPsApi.class);
Returns a list of IPs assigned to your account.
IPsResult result = mailgunIPsApi.getAllIPs();
Return only dedicated IPs if param
dedicated
set to true
, otherwise return all IPs.
IPsResult result = mailgunIPsApi.getDedicatedIPs(true);
Returns information about the specified IP.
IPResult result = mailgunIPsApi.getSpecifiedIP(IP);
Returns a list of IPs currently assigned to the specified domain.
IPsResult result = mailgunIPsApi.getDomainIPs(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 an IP from the domain specified.
ResponseWithMessage response = mailgunIPsApi.unassignIPFromDomain(DOMAIN, IP);
More examples - MailgunIPsIntegrationTest
MailgunEventsApi Mailgun tracks every event that happens to your emails and makes this data available to you through the Events API.
MailgunEventsApi mailgunEventsApi = MailgunClient.config(PRIVATE_API_KEY)
.createApi(MailgunEventsApi.class);
Get all events that happen to your emails.
EventsResponse response = mailgunEventsApi.getAllEvents(DOMAIN);
Get specified events that happen to your emails.
EventsQueryOptions eventsQueryOptions = EventsQueryOptions.builder()
.event(EventType.DELIVERED)
.build();
EventsResponse response = mailgunEventsApi.getEvents(DOMAIN, eventsQueryOptions);
Fetches the next page of log records, assuming that the previous request returned the pageId
.
EventsResponse response = mailgunEventsApi.getEvents(DOMAIN, pageId);
More examples - MailgunEventsIntegrationTest
MailgunStatisticsApi Mailgun collects many different events and generates event statistics available via this API.
Mailgun Statistics documentation.
MailgunStatisticsApi mailgunStatisticsApi = MailgunClient.config(PRIVATE_API_KEY)
.createApi(MailgunStatisticsApi.class);
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
MailgunTagsApi Mailgun lets you tag each outgoing message with a custom value and provides statistics on the tag level.
MailgunTagsApi mailgunTagsApi = MailgunClient.config(PRIVATE_API_KEY)
.createApi(MailgunTagsApi.class);
Returns a list of tags for a domain.
TagsResult result = mailgunTagsApi.getAllTags(DOMAIN);
Returns a given tag.
TagsItem result = mailgunTagsApi.getTag(DOMAIN, TAG);
Updates a given tag with the information provided.
TagUpdateRequest request = TagUpdateRequest.builder()
.description(newDescription)
.build();
ResponseWithMessage response = mailgunTagsApi.updateTag(DOMAIN, TAG, request);
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);
Deletes the tag.
ResponseWithMessage response = mailgunTagsApi.deleteTag(DOMAIN, TAG);
Returns a list of countries of origin for a given domain for different event types.
TagCountriesResponse response = mailgunTagsApi.listTagCountries(DOMAIN, TAG);
Returns a list of email providers for a given domain for different event types.
TagProvidersResponse response = mailgunTagsApi.listTagProviders(DOMAIN, TAG);
Returns a list of devices for a given domain that have triggered event types.
TagDevicesResponse response = mailgunTagsApi.listTagDevices(DOMAIN, TAG);
More examples - MailgunTagsApiIntegrationTest
Mailgun Suppressions documentation.
Mailgun Suppression Bounces documentation.
MailgunSuppressionBouncesApi mailgunSuppressionBouncesApi = MailgunClient.config(PRIVATE_API_KEY)
.createApi(MailgunSuppressionBouncesApi.class);
Returns a list of bounces for a domain.
BouncesResponse response = suppressionBouncesApi.getBounces(DOMAIN, MAXIMUM_NUMBER_OF_RECORDS);
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 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 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 a list of bounces.
BouncesListImportRequest request = BouncesListImportRequest.builder()
.file(new File("/path/to/file"))
.build();
ResponseWithMessage result = suppressionBouncesApi.importBounceList(MAIN_DOMAIN, request);
Delete a single bounce.
ResponseWithMessage response = suppressionBouncesApi.deleteBounce(DOMAIN, ADDRESS);
Delete all bounced email addresses for a domain.
ResponseWithMessage response = suppressionBouncesApi.deleteAllBounces(DOMAIN);
More examples - MailgunSuppressionBouncesApiIntegrationTest
MailgunSuppressionComplaintsApi
Mailgun Suppression Complaints documentation.
MailgunSuppressionComplaintsApi mailgunSuppressionComplaintsApi = MailgunClient.config(PRIVATE_API_KEY)
.createApi(MailgunSuppressionComplaintsApi.class);
Returns a list of complaints for a domain.
ComplaintsItemResponse response = suppressionComplaintsApi.getAllComplaints(DOMAIN, MAXIMUM_NUMBER_OF_RECORDS);
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 an address to the complaints list.
ComplaintsSingleItemRequest request = ComplaintsSingleItemRequest.builder()
.address(EMAIL)
.createdAt(DATE_TIME)
.build();
SuppressionResponse response = suppressionComplaintsApi.addAddressToComplaintsList(DOMAIN, request);
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 a list of complaints.
ComplaintsListImportRequest request = ComplaintsListImportRequest.builder()
.file(new File("/path/to/file"))
.build();
ResponseWithMessage result = suppressionComplaintsApi.importComplaintsList(MAIN_DOMAIN, request);
Remove Address From Complaints.
SuppressionResponse response = suppressionComplaintsApi.removeAddressFromComplaints(DOMAIN, EMAIL);
More examples - MailgunSuppressionComplaintsApiIntegrationTest
MailgunSuppressionUnsubscribeApi
Mailgun Suppression Unsubscribe documentation.
MailgunSuppressionUnsubscribeApi mailgunSuppressionUnsubscribeApi = MailgunClient.config(PRIVATE_API_KEY)
.createApi(MailgunSuppressionUnsubscribeApi.class);
Returns a list of unsubscribes for a domain.
UnsubscribeItemResponse response = suppressionUnsubscribeApi.getAllUnsubscribe(DOMAIN, MAXIMUM_NUMBER_OF_RECORDS);
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 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 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 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 an address from the unsubscribes list.
SuppressionResponse response = suppressionUnsubscribeApi.removeAddressFromUnsubscribeTag(DOMAIN, EMAIL, TAG);
Completely remove an address from the unsubscribes list.
SuppressionResponse response = suppressionUnsubscribeApi.removeAddressFromUnsubscribeList(DOMAIN, EMAIL);
More examples - MailgunSuppressionUnsubscribeApiIntegrationTest
MailgunSuppressionWhitelistsApi
Mailgun Suppression Whitelists documentation.
MailgunSuppressionWhitelistsApi mailgunSuppressionWhitelistsApi = MailgunClient.config(PRIVATE_API_KEY)
.createApi(MailgunSuppressionWhitelistsApi.class);
Returns a list of whitelists for a domain.
WhitelistsItemResponse response = suppressionWhitelistsApi.getAllWhitelists(DOMAIN, MAXIMUM_NUMBER_OF_RECORDS);
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 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 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 a single record from whitelist table.
WhitelistsRemoveRecordResponse response = suppressionWhitelistsApi.removeRecordFromWhitelists(DOMAIN, EMAIL);
More examples - MailgunSuppressionWhitelistsApiIntegrationTest
MailgunRoutesApi allows you to work with routes programmatically.
MailgunRoutesApi mailgunRoutesApi = MailgunClient.config(PRIVATE_API_KEY)
.createApi(MailgunRoutesApi.class);
Fetches the list of routes.
RoutesPageRequest pageRequest = RoutesPageRequest.builder()
.limit(2)
.skip(2)
.build();
RoutesListResponse response = mailgunRoutesApi.getRoutesList(pageRequest);
Returns a single route object based on its ID.
SingleRouteResponse response = mailgunRoutesApi.getSingleRoute(ROUTE_ID);
Creates a new route.
RoutesRequest routesRequest = RoutesRequest.builder()
.priority(2)
.description(DESCRIPTION)
.expression("match_recipient('.*[email protected]')")
.action("forward('" + EMAIL_2 + "')")
.action("forward('" + EMAIL_3 + "')")
.actions(Arrays.asList("forward('https://myhost.com/messages')", "stop()"))
.build();
RoutesResponse response = mailgunRoutesApi.createRoute(routesRequest);
Updates a given route by ID.
RoutesRequest routesRequest = RoutesRequest.builder()
.priority(1)
.action("forward('" + EMAIL + "')")
.build();
Route result = mailgunRoutesApi.updateRoute(routeId, routesRequest);
Deletes a route based on the id.
ResponseWithMessage response = mailgunRoutesApi.deleteRoute(ROUTE_ID);
More examples - MailgunRoutesIntegrationTest
MailgunWebhooksApi allows you to create, access, and delete webhooks programmatically.
Mailgun Webhooks documentation.
MailgunWebhooksApi mailgunWebhooksApi = MailgunClient.config(PRIVATE_API_KEY)
.createApi(MailgunWebhooksApi.class);
Returns a list of webhooks set for the specified domain.
WebhookListResult result = mailgunWebhooksApi.getAllWebhooks(DOMAIN);
Return details about a webhook specified in the URL.
WebhookDetailsResult result = mailgunWebhooksApi.getWebhookDetails(DOMAIN, WebhookName.CLICKED);
Creates a new webhook.
WebhookRequest request = WebhookRequest.builder()
.webhookName(WebhookName.CLICKED)
.url(WEBHOOK_URL)
.build();
WebhookResult result = mailgunWebhooksApi.createNewWebhook(DOMAIN, request);
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);
Deletes an existing webhook.
WebhookResult result = mailgunWebhooksApi.deleteWebhook(DOMAIN, WebhookName.CLICKED);
More examples - MailgunWebhooksApiIntegrationTest
You can programmatically create mailing lists using MailgunMailingListApi
Mailgun Mailing Lists documentation.
MailgunMailingListApi mailgunMailingListApi = MailgunClient.config(PRIVATE_API_KEY)
.createApi(MailgunMailingListApi.class);
Returns mailing lists under your account.
MailingListDataResponse response = mailgunMailingListApi.getMailingList(MAXIMUM_NUMBER_OF_RECORDS);
Returns a single mailing list by a given address.
SingleMailingListResponse response = mailgunMailingListApi.getMailingListByAddress(ADDRESS);
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 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);
Deletes a mailing list.
DeleteMailingListResponse response = mailgunMailingListApi.deleteMailingList(MAILING_LIST_ADDRESS);
Verify all the members of the mailing list.
MailingListVerificationResponse response = mailgunMailingListApi.verifyMailingListMembers(MAILING_LIST_ADDRESS);
Retrieve the current status of the mailing list verification job.
MailingListVerificationStatusResponse response = mailgunMailingListApi.getMailingListVerificationJobStatus(MAILING_LIST_ADDRESS);
Cancel an active mailing list verification job.
String result = mailgunMailingListApi.cancelActiveMailingListVerificationJob(MAILING_LIST_ADDRESS);
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);
Returns the first page of the list of members in the given mailing list.
MailingListMembersRequest request = MailingListMembersRequest.builder()
.limit(10)
.page("first")
.build();
MailingListMembersResponse response = mailgunMailingListApi.getMailingListMembers(MAILING_LIST_ADDRESS, request);
Returns the last page of the list of members in the given mailing list.
MailingListMembersRequest request = MailingListMembersRequest.builder()
.limit(10)
.page("last")
.build();
MailingListMembersResponse response = mailgunMailingListApi.getMailingListMembers(MAILING_LIST_ADDRESS, request);
Returns the next page after specified email of the list of members in the given mailing list.
MailingListMembersResponse response = mailgunMailingListApi.getMailingListMembers(MAILING_LIST_ADDRESS, request);
memberAddress = response.getItems().stream()
.reduce((first, last) -> last)
.orElseThrow(NoSuchElementException::new)
.getAddress();
MailingListMembersRequest request = MailingListMembersRequest.builder()
.limit(10)
.page("next")
.address(memberAddress)
.build();
response = mailgunMailingListApi.getMailingListMembers(MAILING_LIST_ADDRESS, request);
Returns the previous page before specified email of the list of members in the given mailing list.
MailingListMembersResponse response = mailgunMailingListApi.getMailingListMembers(MAILING_LIST_ADDRESS, request);
memberAddress = response.getItems().stream()
.findFirst()
.orElseThrow(NoSuchElementException::new)
.getAddress();
MailingListMembersRequest request = MailingListMembersRequest.builder()
.limit(10)
.page("prev")
.address(memberAddress)
.build();
response = mailgunMailingListApi.getMailingListMembers(MAILING_LIST_ADDRESS, request);
Retrieves a mailing list member.
MailingListMemberResponse response = mailgunMailingListApi.getMailingListMember(MAILING_LIST_ADDRESS, MEMBER_EMAIL);
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);
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);
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 a mailing list member.
MailingListMemberResponse response = mailgunMailingListApi.deleteMemberFromMailingList(MAILING_LIST_ADDRESS, MEMBER_EMAIL);
More examples - MailgunMailingListApiIntegrationTest
MailgunTemplatesApi allows you to access information regarding the IPs allocated to your Mailgun account that is used for outbound sending.
Mailgun Templates documentation.
MailgunTemplatesApi mailgunTemplatesApi = MailgunClient.config(PRIVATE_API_KEY)
.createApi(MailgunTemplatesApi.class);
Returns a list of stored templates for the domain (limit to 10 entries).
TemplatesResult result = mailgunTemplatesApi.getAllTemplates(DOMAIN);
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);
Returns metadata information about a stored template.
TemplateResponse response = mailgunTemplatesApi.getTemplate(DOMAIN, TEMPLATE_NAME);
Returns the content of the active version of the template with metadata information.
TemplateWithVersionResponse response = mailgunTemplatesApi.getActiveTemplateVersionContent(DOMAIN, TEMPLATE_NAME);
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 the metadata information of the template.
TemplateStatusResponse response = mailgunTemplatesApi.updateTemplate(DOMAIN, TEMPLATE_NAME, TEMPLATE_DESCRIPTION);
Delete the template.
TemplateStatusResponse response = mailgunTemplatesApi.deleteTemplate(DOMAIN, TEMPLATE_NAME);
Delete all stored templates for the domain.
ResponseWithMessage response = mailgunTemplatesApi.deleteAllTemplatesInDomain(DOMAIN);
Returns a list of stored versions of the template.
TemplateAllVersionsResponse response = mailgunTemplatesApi.getAllTemplateVersions(DOMAIN, TEMPLATE_NAME);
Retrieve information and content of specified version of the template.
TemplateWithVersionResponse response = mailgunTemplatesApi.getSpecifiedVersionTemplateContent(DOMAIN, TEMPLATE_NAME, TEMPLATE_VERSION_TAG);
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 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 a specific version of the template.
TemplateVersionResponse response = mailgunTemplatesApi.deleteSpecificTemplateVersion(DOMAIN, TEMPLATE_NAME, TEMPLATE_VERSION_TAG);
More examples - MailgunTemplatesIntegrationTest
MailgunEmailVerificationApi is an email address verification service.
Mailgun Email Validation/Verification documentation.
MailgunEmailVerificationApi mailgunEmailVerificationApi = MailgunClient.config(PRIVATE_API_KEY)
.createApi(MailgunEmailVerificationApi.class);
Given an arbitrary address, validates address based on defined checks.
AddressValidationResponse result = mailgunEmailVerificationApi.validateAddress(EMAIL);
Get list of all bulk verification jobs.
BulkVerificationJobListResponse result = mailgunEmailVerificationApi.getBulkVerificationJobList();
Check the current status of a bulk verification job.
BulkVerificationJobStatusResponse result = mailgunEmailVerificationApi.getBulkVerificationJobStatus(LIST_NAME);
Create a bulk verification job.
BulkVerificationStatusRequest request = BulkVerificationStatusRequest.builder()
.file(new File("/path/to/file"))
.build();
BulkVerificationCreatingResponse result = mailgunEmailVerificationApi.createBulkVerificationJob(LIST_NAME, request);
Cancel current running bulk verification job.
String result = mailgunEmailVerificationApi.cancelBulkVerificationJob(LIST_NAME);
Get list of all bulk verification previews.
BulkVerificationPreviewListResponse result = mailgunEmailVerificationApi.getBulkVerificationPreviewList();
Check the current status of a bulk verification preview.
BulkVerificationPreviewResponse result = mailgunEmailVerificationApi.getBulkVerificationPreviewStatus(LIST_NAME);
Create a bulk verification preview.
BulkVerificationStatusRequest request = BulkVerificationStatusRequest.builder()
.file(new File("/path/to/file"))
.build();
BulkVerificationCreatingResponse result = mailgunEmailVerificationApi.createBulkVerificationPreview(LIST_NAME, request);
Delete a bulk verification preview.
Response result = mailgunEmailVerificationApi.deleteBulkVerificationPreview(LIST_NAME);
More examples - MailgunEmailVerificationIntegrationTest
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.
MailgunSeedListApi mailgunSeedListApi = MailgunClient.config(PRIVATE_API_KEY)
.createApi(MailgunSeedListApi.class);
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);
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 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);
You can select a single seed list with this endpoint.
SingleSeedListResponse result = mailgunSeedListApi.getSeedList(TARGET_EMAIL);
Get all iterable attributes of seed lists.
SeedListsAttributesResponse result = mailgunSeedListApi.getSeedListsAttributes();
Get all values of a specific attribute of your seed lists.
SeedListsAttributesResponse result = mailgunSeedListApi.getSeedListsAttribute(ATTRIBUTE_NAME);
Get all available filters for seed lists.
SeedListsFiltersResponse result = mailgunSeedListApi.getSeedListFilters();
Delete a seed list.
Response result = mailgunSeedListApi.deleteSeedListFeignResponse(TARGET_EMAIL);
Test results are generated when a message has been received at the target_email.
Response result = mailgunSeedListApi.getResultsFeignResponse();
Get Available Result Filters.
Response result = mailgunSeedListApi.getAvailableResultFiltersFeignResponse();
Get all iterable attributes of results.
SeedListsAttributesResponse result = mailgunSeedListApi.getResultsAttributes();
Get all values of a specific attribute of your results lists.
SeedListsAttributesResponse result = mailgunSeedListApi.getResultsAttribute(ATTRIBUTE);
Get a specific result.
Response result = mailgunSeedListApi.getSpecificResultFeignResponse(RID);
Delete a result.
Response result = mailgunSeedListApi.deleteResultFeignResponse(RID);
More examples - MailgunSeedListIntegrationTest
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
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.