Java sending Mutliple Files attachment in mailgun

Viewed 1928

I'm trying to send email with mailgun and attaching two files or more with this email:

public static JsonNode sendComplexMessage() throws UnirestException {

        HttpResponse<JsonNode> request = Unirest.post("https://api.mailgun.net/v3/" + YOUR_DOMAIN_NAME + "/messages")
                .basicAuth("api", API_KEY)
                .queryString("from", "Excited User <USER@YOURDOMAIN.COM>")
                .queryString("to", "alice@example.com")
                .queryString("cc", "bob@example.com")
                .queryString("bcc", "joe@example.com")
                .queryString("subject", "Hello")
                .queryString("text", "Testing out some Mailgun awesomeness!")
                .queryString("html", "<html>HTML version </html>")
                .field("attachment", new File("/temp/folder/test.txt"))
                .asJson();

        return request.getBody();

This example is from Mailgun Docs, but it send just single file. I need to send multiple emails.

Any help is appreciated.

3 Answers

instead of putting a single file object ,put an arrayList of Files and it's gonna to work like this :

.field("attachment", Arrays.asList(file1,file2))

you can create a list,iterate over it by loop and then send it

List<File> listFiles=new ArrayList<>();
// fill it

.field("attachment", listFiles)

You can use .field("attachment", new File("FILE_NAME")) again to send one more attachement as shown in below code:

public static JsonNode sendComplexMessage() throws UnirestException {
    HttpResponse<JsonNode> request = Unirest.post("https://api.mailgun.net/v3/" + YOUR_DOMAIN_NAME + "/messages")
                    .basicAuth("api", API_KEY)
                    .queryString("from", "Excited User <USER@YOURDOMAIN.COM>")
                    .queryString("to", "alice@example.com")
                    .queryString("cc", "bob@example.com")
                    .queryString("bcc", "joe@example.com")
                    .queryString("subject", "Hello")
                    .queryString("text", "Testing out some Mailgun awesomeness!")
                    .queryString("html", "<html>HTML version </html>")

                    // attaching test.txt and test2.txt files
                    .field("attachment", new File("/temp/folder/test.txt"))
                    .field("attachment", new File("/temp/folder/test2.txt"))

                    .asJson();
}

If you have file names in a list you can do this:

List<String> attachmentNames = ...
for (String attachmentName : attachmentNames) {
     multipartBody.field("attachment", new File(attachmentName));
}
Related