Skip to content Skip to sidebar Skip to footer

MailGun Android HttpUrlConnection Constant Error 400

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

Solution 1:

Try this:

String apiKey = "api:{key}"
String authHeader = "Basic " + Base64.encodeToString(apiKey.getBytes(), Base64.DEFAULT);
    try {
        String data = URLEncoder.encode("from", "UTF-8") + "=" + URLEncoder.encode("from@from.com", "UTF-8");
        data += "&" + URLEncoder.encode("to", "UTF-8") + "=" + URLEncoder.encode("to@to.com", "UTF-8");
        data += "&" + URLEncoder.encode("subject", "UTF-8") + "=" + URLEncoder.encode("subject", "UTF-8");
        data += "&" + URLEncoder.encode("text", "UTF-8") + "=" + URLEncoder.encode("msg body", "UTF-8");
        URL u = new URL("https://api.mailgun.net/{DOMAIN}/messages");
        HttpURLConnection restConnection = (HttpURLConnection) u.openConnection();
        restConnection.setRequestMethod("POST");
        restConnection.setDoOutput(true);
        restConnection.setRequestProperty("Authorization", authHeader);
        OutputStreamWriter w = new OutputStreamWriter(restConnection.getOutputStream());
        w.write(data);
        w.flush();
        w.close();
        int status = restConnection.getResponseCode();

        // switch statement to catch HTTP 200 and 201 errors
        switch (status) {
            case 200:
                // live connection to your REST service is established here using getInputStream() method
                BufferedReader br = new BufferedReader(new InputStreamReader(restConnection.getInputStream()));

                // create a new string builder to store json data returned from the REST service
                StringBuilder sb = new StringBuilder();
                String line;

                // loop through returned data line by line and append to stringbuilder 'sb' variable
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                br.close();

                // remember, you are storing the json as a stringy
                try {
                    json = sb.toString();
                } catch (Exception e) {
                    Log.e(TAG, "Error parsing data " + e.toString());
                }
                // return JSON String containing data to Tweet activity (or whatever your activity is called!)
                break;
            case 400:
                Log.d(TAG, "Bad request");
                break;
            case 401:
                Log.d(TAG, "Unauthorized");
                break;
            case 402:
                Log.d(TAG, "Request Failed");
                break;
            case 404:
                Log.d(TAG, "404");
                break;
            case 500:
            case 502:
            case 503:
            case 504:
                Log.d(TAG, "Mailgun fail");
                break;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

Solution 2:

If you want to use MailGun on Android just do few steps:

1) Check this library. And implement it.

2) This library is for Java, not for Android. So you need to add 'configurations' to your gradle file and it should look like this:

dependencies {
   compile fileTree(dir: 'libs', include: ['*.jar'])
   compile 'net.sargue:mailgun:1.3.2'
}

configurations {
   compile.exclude group: 'javax.inject', module: 'javax.inject'
}

more information here

3) So now you can use this library: (don't forget to run it in background thread)

Configuration configuration = new Configuration()
    .domain("somedomain.com")
    .apiKey("key-xxxxxxxxxxxxxxxxxxxxxxxxx")
    .from("Test account", "postmaster@somedomain.com");
Response response = Mail.using(configuration)
    .to("marty@mcfly.com")
    .subject("This message has an text attachment")
    .text("Please find attached a file.")
    .multipart()
    .attachment(new File("/path/to/image.jpg"))
    .build()
    .send();

Post a Comment for "MailGun Android HttpUrlConnection Constant Error 400"