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

时间:2018-06-23 22:32:05

标签: java sendgrid

我正在尝试在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);

执行此操作的正确方法是什么?

1 个答案:

答案 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);

}