问题
I am trying to attach a local file at path /Users/david/Desktop/screenshot5.png
in sendgrid.
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);
What would be the proper way to do this?
回答1:
You added the file path.
You should add the file content instead:
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);
}
来源:https://stackoverflow.com/questions/51005561/adding-attachment-from-local-filepath-in-sendmail