在Sendmail中从本地文件路径添加附件

Adding attachment from local filepath in sendmail(在Sendmail中从本地文件路径添加附件)

本文介绍了在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);

}

这篇关于在Sendmail中从本地文件路径添加附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在Sendmail中从本地文件路径添加附件

基础教程推荐