After a complete and utter failure to implement code with Retrofit, I have used Android's HttpURLConnection class to try and send an email through MailGun. However whatever I seem to do I get error 400 bad request back. I do not know what I am doing wrong - similar code seems to be working perfectly within iOS. The 4 lines commented out make no difference. Hardcoding the values for from and to did not fix it either. I have tried using application/json for Content-Type as well. Any pointers in the right direction would be appreciated!
URL u = new URL("https://api.mailgun.net/v3/companyname.com/messages");
HttpURLConnection restConnection = (HttpURLConnection) u.openConnection();
restConnection.setRequestMethod("POST");
String authHeader = "Basic " + Base64.encodeToString(apiKey.getBytes(), Base64.DEFAULT);
restConnection.setRequestProperty("Authorization", authHeader);
restConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
restConnection.setRequestProperty("from", "Company Name <noreply@companyname.com>");
restConnection.setRequestProperty("to", "myemailaddress@gmail.com");
restConnection.setRequestProperty("subject", "test");
restConnection.setRequestProperty("text", "test");
//restConnection.setUseCaches(false);
//restConnection.setAllowUserInteraction(false);
//restConnection.setConnectTimeout(10000);
//restConnection.setReadTimeout(10000);
restConnection.connect();
int status = restConnection.getResponseCode();
See Question&Answers more detail:os