Adding attachment from local filepath in sendmail

爱⌒轻易说出口 提交于 2020-01-06 06:28:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!