How to attach multiple files to email using Mailgun API in Java

I need help with sending emails through Mailgun that include several file attachments. Right now I can only get one file to attach properly.

Here’s my current code:

public static JsonNode sendEmailWithAttachments() throws UnirestException {
    HttpResponse<JsonNode> response = Unirest.post("https://api.mailgun.net/v3/" + DOMAIN_NAME + "/messages")
            .basicAuth("api", SECRET_KEY)
            .queryString("from", "Support Team <[email protected]>")
            .queryString("to", "[email protected]")
            .queryString("subject", "Your requested documents")
            .queryString("text", "Please find attached files below.")
            .queryString("html", "<p>Please find attached files below.</p>")
            .field("attachment", new File("/documents/report.pdf"))
            .asJson();
    
    return response.getBody();
}

This works fine for one attachment but I want to include multiple files like a PDF report and an Excel spreadsheet in the same email. What’s the proper way to add more than one attachment using the Mailgun API?

Thanks for any suggestions.

Alex_Brave’s right. You can chain multiple .field() calls with the same “attachment” parameter to include several files. I’ve used this method in production for two years - works great. Just double-check your file paths are valid before hitting the API, or you’ll get weird error messages from Mailgun. Also, there’s a 25MB limit for all attachments combined, so watch out with larger files. Pro tip I learned the hard way: always check file.exists() before adding each attachment to avoid silent failures.

just add more .field(‘attachment’, new File(‘path/to/your/file’)) for each file you want to attach. like .field(‘attachment’, new File(‘/path/file1.pdf’)).field(‘attachment’, new File(‘/path/file2.xlsx’)). that’s how I fixed it!

Hit this exact problem last month building a document delivery system. What tripped me up at first - each attachment needs its own field call, but they all use the same parameter name “attachment”. Your code’s on the right track, just extend it. Try .field("attachment", new File("/documents/report.pdf")).field("attachment", new File("/documents/spreadsheet.xlsx")) - should work perfectly. Heads up though: I wasted hours on a file permissions issue. Make sure the Java process can actually read your files. And if you’ve got dynamic file lists, just loop through your File objects and call the field method for each one.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.