Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java sending Mutliple Files attachment in mailgun

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 <[email protected]>")
                .queryString("to", "[email protected]")
                .queryString("cc", "[email protected]")
                .queryString("bcc", "[email protected]")
                .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.

like image 621
Ahmed E. Eldeeb Avatar asked Sep 15 '18 13:09

Ahmed E. Eldeeb


2 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)
like image 183
Mikhail Fayez Avatar answered Oct 20 '22 17:10

Mikhail Fayez


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 <[email protected]>")
                    .queryString("to", "[email protected]")
                    .queryString("cc", "[email protected]")
                    .queryString("bcc", "[email protected]")
                    .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();
}
like image 32
Yug Singh Avatar answered Oct 20 '22 17:10

Yug Singh