You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java中使用Graph API添加本地邮件附件(.txt/.pdf/.zip等)

解决本地附件路径指定问题

要正确指定本地系统的附件文件路径并读取文件内容,你可以按以下步骤调整代码:

  • 取消路径定义的注释并替换为实际路径
    根据你的操作系统,使用对应的路径格式:

    • macOS/Linux:直接使用正斜杠分隔的绝对路径,比如 /Users/your-username/Desktop/Text.txt
    • Windows:使用双反斜杠(转义后的斜杠)分隔的路径,比如 C:\\Users\\your-username\\Desktop\\Text.txt
  • 处理文件读取的IO异常
    文件读取操作会抛出IOException,你需要在方法上声明抛出该异常,或者在代码中捕获处理。

  • 可选:使用Java标准库读取文件
    如果你不想依赖Apache Commons IO的FileUtils,可以用Java自带的Files.readAllBytes方法,效果一致。

调整后的完整代码示例:

private static void sendMailWithAttachment(String sFrom, String sSubject, String sContent, BodyType sContentType) throws IOException {
        
    final Message message = new Message();
    message.subject = sSubject;
    message.body = new ItemBody();
    message.body.content = sContent;
    message.body.contentType = sContentType;
    
    LinkedList<Attachment> attachmentsList = new LinkedList<>();
    FileAttachment fileAttachment = new FileAttachment();
    
    fileAttachment.name = "Example text file";
    // 替换为你实际的本地文件路径
    Path path = Paths.get("/Users/your-username/Desktop/Text.txt");
    // 使用Java标准库读取文件字节,或者保留FileUtils.readAllBytes(path)(需确保依赖Apache Commons IO)
    fileAttachment.contentBytes = Files.readAllBytes(path);
    
    fileAttachment.oDataType = "#microsoft.graph.fileAttachment";
    attachmentsList.add(fileAttachment);
    
    AttachmentCollectionResponse attachmentCollectionResponse = new AttachmentCollectionResponse();
    attachmentCollectionResponse.value = attachmentsList;
    AttachmentCollectionPage attachmentCollectionPage = new AttachmentCollectionPage(attachmentCollectionResponse, null);
    message.attachments = attachmentCollectionPage;
    
    _appClient.users("xxyy@xxyy.com")
        .sendMail(UserSendMailParameterSet
            .newBuilder()
            .withMessage(message)
            .withSaveToSentItems(null)
            .build())
        .buildRequest()
        .post();
}

注意事项:

  • 确保程序有访问该文件路径的权限,否则会抛出权限相关异常
  • 如果使用相对路径,要确认程序的工作目录是否正确,建议优先使用绝对路径避免路径混乱

内容的提问来源于stack exchange,提问作者Mani Bellamkonda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 09:52:42