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

如何使用MS Graph Java SDK创建带附件的Message对象?

解决MS Graph Java SDK 5.x发送带内嵌附件邮件的问题

针对你遇到的两个核心问题,结合SDK 5.42.0的特性,给出具体解决方案:

1. 找不到contentBytes字段的原因及解决

在SDK 5.x中,Attachment是抽象类,不能直接实例化,你需要使用其具体实现类FileAttachment(用于文件类型的附件,包括内嵌图片),contentBytes字段属于FileAttachment的属性,而非基类Attachment。

同时注意:

  • 不需要手动设置id,该字段由Graph服务生成
  • 关联HTML内嵌图片的是contentId字段,对应HTML中的cid:标识
  • contentType需使用标准MIME类型(如image/png),而非文件后缀.png

2. 创建AttachmentCollectionPage赋值给message.attachments

AttachmentCollectionPage可以直接通过构造方法传入Attachment列表创建,无需复杂操作。

修改后的完整代码示例

import com.microsoft.graph.models.*;
import com.microsoft.graph.requests.AttachmentCollectionPage;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.Base64;

// 收件人配置
Recipient recipient = new Recipient();
EmailAddress emailAddress = new EmailAddress();
emailAddress.setAddress("tom@mail.com");
recipient.setEmailAddress(emailAddress);
List<Recipient> recipients = List.of(recipient);

// 邮件正文(内嵌图片引用cid)
ItemBody body = new ItemBody();
body.setContentType(BodyType.HTML);
body.setContent("<html><body>my image:<br><img src='cid:my_image_CID'></body></html>");

// 内嵌图片附件(使用FileAttachment)
FileAttachment inlineImage = new FileAttachment();
inlineImage.setIsInline(true);
inlineImage.setContentType("image/png"); // 标准MIME类型
inlineImage.setContentId("my_image_CID"); // 对应HTML中的cid标识

// 读取本地图片并转为Base64编码的字符串
try {
    byte[] imageBytes = Files.readAllBytes(Paths.get("/path/to/your/image.png"));
    inlineImage.setContentBytes(Base64.getEncoder().encodeToString(imageBytes));
} catch (Exception e) {
    e.printStackTrace();
}

// 组装邮件对象
Message message = new Message();
message.setSubject("my subject");
message.setBody(body);
message.setToRecipients(recipients);
// 创建AttachmentCollectionPage并赋值
message.setAttachments(new AttachmentCollectionPage(Collections.singletonList(inlineImage)));

// 发送邮件(示例,需确保graphClient已正确初始化)
graphClient.me().sendMail(UserSendMailParameterSet.newBuilder()
        .withMessage(message)
        .withSaveToSentItems(true)
        .build())
        .post();

关键注意点

  • 确保图片文件路径正确,读取时处理IO异常
  • contentBytes需要传入Base64编码的字符串,不能直接传入字节数组
  • 若需添加多个附件,只需在Collections.singletonList中替换为包含多个Attachment实例的列表即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 01:35:26