在Sendmail中从本地文件路径添加附件
我正在尝试将本地文件附加到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);
执行此操作的正确方法是什么?
解决方案
您添加了文件路径。
您应该改为添加文件内容:
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);
}
相关文章