我正在尝试在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);
执行此操作的正确方法是什么?
答案 0 :(得分: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);
}