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:

StringapiKey="api:{key}"StringauthHeader="Basic " + Base64.encodeToString(apiKey.getBytes(), Base64.DEFAULT);
    try {
        Stringdata= 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");
        URLu=newURL("https://api.mailgun.net/{DOMAIN}/messages");
        HttpURLConnectionrestConnection= (HttpURLConnection) u.openConnection();
        restConnection.setRequestMethod("POST");
        restConnection.setDoOutput(true);
        restConnection.setRequestProperty("Authorization", authHeader);
        OutputStreamWriterw=newOutputStreamWriter(restConnection.getOutputStream());
        w.write(data);
        w.flush();
        w.close();
        intstatus= restConnection.getResponseCode();

        // switch statement to catch HTTP 200 and 201 errorsswitch (status) {
            case200:
                // live connection to your REST service is established here using getInputStream() methodBufferedReaderbr=newBufferedReader(newInputStreamReader(restConnection.getInputStream()));

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

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

                // remember, you are storing the json as a stringytry {
                    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;
            case400:
                Log.d(TAG, "Bad request");
                break;
            case401:
                Log.d(TAG, "Unauthorized");
                break;
            case402:
                Log.d(TAG, "Request Failed");
                break;
            case404:
                Log.d(TAG, "404");
                break;
            case500:
            case502:
            case503:
            case504:
                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"