Java 在 mailgun 中发送多个文件附件

Java sending Mutliple Files attachment in mailgun

我正在尝试使用 mailgun 发送电子邮件并使用此电子邮件附加两个或更多文件:

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();

此示例来自 Mailgun Docs,但它只发送单个文件。我需要发送多封电子邮件。

感谢任何帮助。

您可以再次使用.field("attachment", new File("FILE_NAME"))发送一个附件,如下代码所示:

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();
}

不是放置单个文件对象,而是放置一个文件数组列表,它将像这样工作:

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

你可以创建一个列表,循环遍历它然后发送它

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

.field("attachment", listFiles)

如果列表中有文件名,您可以这样做:

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