在sendmail中添加本地文件路径的附件

问题描述 投票:0回答:1

我试图在sendgrid路径/Users/david/Desktop/screenshot5.png附加本地文件。

    Mail mail = new Mail(from, subject, to, message);

    // add an attachment
    Attachments attachments = new Attachments();
    Base64 x = new Base64();
    String encodedString = x.encodeAsString("/Users/david/Desktop/screenshot5.png");
    attachments.setContent(encodedString);
    attachments.setDisposition("attachment");
    attachments.setFilename("screenshot5.png");
    attachments.setType("image/png");

    mail.addAttachments(attachments);

这样做的正确方法是什么?

java sendgrid
1个回答
0
投票

您添加了文件路径。 您应该添加文件内容:

Mail mail = new Mail(from, subject, to, message);

// add an attachment
Attachments attachments = new Attachments();
File file = new File("/Users/david/Desktop/screenshot5.png");
byte[] fileContent = Files.readAllBytes(file.toPath());
String encodedString = Base64.getEncoder().encodeToString(fileContent);
attachments.setContent(encodedString);
attachments.setDisposition("attachment");
attachments.setFilename("screenshot5.png");
attachments.setType("image/png");

mail.addAttachments(attachments);

}

© www.soinside.com 2019 - 2024. All rights reserved.