Updated Sat, Nov 18, 2017
Mailgun Manager API project is a partial Java library implementation of Mailgun’s API. It provides a single interface to perform common Mailgun API operations and simplifies access by abstracting the lower level HTTP programming code.
Mailgun Manager makes easy to:
- Send messages to mailing lists or individuals
- Get campaigns and their history (events)
- Save campaign events to a CSV file
- Add members to a mailing list (one a time or in-bulk)
- Fetch, delete, unsubscribe, and update mailing list members
- Discover invalid email addresses unidentified by other libraries such as
EmailValidator
in Apache Commons
Before performing API operations for the first time, you'll need to either configure Mailgun in the mailgun.properties
file or setup an account programmatically.
In the root of your classpath or source directory, create a file named, mailgun.properties
. Set the publicApiKey
, privateApiKey
, and the domain
property values. The API keys can be found in your Mailgun's account settings.
# mailgun.properties file
# Mailgun account properties
baseUri = https://api.mailgun.net/v3
publicApiKey = pubkey-XXXXX
privateApiKey = key-XXXXXX
domain = mg.example.com
Configure a MailgunAccount
object and invoke the MailgunManager.register(MailgunAccount)
method.
//Register Mailgun account info
MailgunAccount account = new MailgunAccount();
account.setBaseUri("https://api.mailgun.net/v3");
account.setDomain("mg.example.com");
account.setPrivateApiKey("key-XXXXXX");
account.setPublicApiKey("pubkey-XXXXX");
MailgunManager.register(account);
Using the Mailgun Manager library is easy.
//Validate an email address
EmailValidationResponse response;
response = MailgunManager.isValidEmail("[email protected]");
//Query the response
if(!response.isValid()) {
//Do something the email is invalid
final String didYouMean = response.getDidYouMean();
if(didYouMean != null) {
//Ask if the meant the value of didYouMean
}
}
Collection<ListInfo> lists = MailgunManager.getMailingLists();
JSONObject objects = new JSONObject();
objects.put("city", "Seattle");
objects.put("created", DateFormat.getInstance().format(new Date()));
objects.put("province", "WA");
ListMemberRequest member = new ListMemberRequest()
.setAddress("[email protected]")
.setName(" John Doe")
.setJSONVar(objects.toString());
boolean success = MailgunManager.addMailingListMember("[email protected]", member)
Unlike the API, Mailgun Manager will accept adding > 1000
members at a time.
List<ListMember> members = ...
boolean success = MailgunManager.addMailingListMembers("[email protected]", members)
ListMemberRequest request = ...
boolean success = MailgunManager.addMailingListMember(sMailingListAddress, request);
List<ListMember> members = getMailingListMembers("[email protected]");
-
Write an Apache Commons BeanUtils Converter class for the var object.
-
Register the converter
-
Then call with the var type Class object:
getMailingListMembers(String, Class)
/////////////////////////////////////// //Fetch members of a mailing list with a var object /////////////////////////////////////// //Write an Apache Commons BeanUtils Converter for the var object Converter varConverter = new org.apache.commons.beanutils.Converter() { @Override public <T> T convert(Class<T> type, Object value) { MyVarObject var = null; if (value instanceof JSONObject) { JSONObject obj = (JSONObject) value; var = new MyVarObject(); try { BeanUtils.populate(var, obj); } catch (IllegalAccessException | InvocationTargetException e) { ContextedRuntimeException cre; cre = new ContextedRuntimeException("Bean population error", e); cre.addContextValue("value", obj); throw cre; } } return type.cast(var); } }; //Register the converter ConvertUtils.register(varConverter, MyVarObject.class) List<ListMember> members = getMailingListMembers("[email protected]", MyVarObject.class);
ListMemberRequest request = ...
//Change the name
request.setName("John Updated");
boolean success = MailgunManager.updateMailingListMember(sMailingListAddress, request);
boolean success;
success = MailgunManager.deleteMailingListMember("[email protected]", "[email protected]")
///////////////////////////////////////
//Send a email
/////////////////////////////////////////
EmailRequest email = new EmailRequest()
.setTo("[email protected]")
.setFrom("[email protected]")
.setSubject("Hello")
.setTextBody("Hello Mary:\n\nThis message was sent from Mailgun Manager for Java.")
.setHeader("X-Test-Class", getClass().getSimpleName());
boolean success = MailgunManager.sendMessage(email);
Campaign campaign = MailgunManager.getCampaign("myCampaignId");
List<Map<String, Object>> events;
events = MailgunManager.getCampaignEvents("myCampaignId");
MailgunManager.saveCampaignEventsToCSV("myCampaignId");
I created this library primarily for two reasons:
- I had a hard time finding a Java implementation of the Mailgun API.
- I was unable to find examples using the latest version of the Jersey framework.
In any case, this project is a work-in-progress.
This project uses Gradle for build automation.
- Install and configure Eclipse IDE for Java EE Developers
- Install and configure the Egit plugin (optional)
- Install and configure the Buildship Eclipse Plugin
Import the project:
- In Eclipse, click File > Import > Git > Projects from Git.
- Then click Next > Clone URI, set the Connection to Git, set the URI, and click Next > Next > Next > Finish.
- Click Import existing projects, click Working Directory, and click Next > Finish.
The MailgunManager
class in the com.rodaxsoft.mailgun
package is a facade class that implements the following methods:
addMailingListMember(String, ListMemberRequest)
addMailingListMembers(String, List<ListMember>)
deleteMailingListMember(String, String)
getCampaign(String)
getCampaignEvents(String)
getMailingListMember(String, String)
getMailingListMembers(String)
getMailingListMembers(String, Class<?>)
getMailingLists()
isValidEmail(String)
register(MailgunAccount)
saveCampaignEventsToCSV(String)
sendMessage(EmailRequest)
unsubscribeMailingListMember(String, String)
updateMailingListMember(String, ListMemberRequest)
Note: Clients must register Mailgun account info before invoking a Mailgun API operation such as adding a member to a mailing list.
See the Javadoc comments in MailgunManager.java
for more details.
See the test cases in the com.rodaxsoft.junit.mailgun
package.
Before running, edit the properties in testcase.properties
file
baseUri = https://api.mailgun.net/v3
publicApiKey = pubkey-XXXXX
privateApiKey = key-XXXXXX
domain = mg.example.com
# Mailing List
mailing.list = [email protected]
email.from = [email protected]
email.to = [email protected]
#Campaign
campaign.id = myid
To reach a milestone for a major release, we'd like contributions for the following:
- Create, update, fetch, and delete a campaign
- Fetch campaign stats, clicks, opens, unsubscribes, and complaints
- Fetch and delete stored messages
- Create, update, and delete mailing lists
Mailgun API routines are implemented as subclasses of the AbstractMailgunRoutine
class. Current implementation class examples include: EmailValidator
, MailSender
, and MailingListManager
.
Contributions can be made by following these steps:
- Fork it!
- Create your feature branch:
git checkout -b my-new-feature
- Commit your changes:
git commit -am 'Add some feature'
- Push to the branch:
git push origin my-new-feature
- Submit a pull request :D
If you have any questions, please don't hesitate to contact me at [email protected].
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.