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

使用Microsoft Graph Client API发送带附件邮件遇RequestBodyRead错误求助

解决Microsoft Graph API发送带附件邮件的"RequestBodyRead"异常

问题分析

你遇到的错误{"error":{"code":"RequestBodyRead","message":"Cannot read the value '0' as a quoted JSON string value."}},根源是附件的ContentBytes序列化方式错误:

  • Microsoft Graph API要求fileAttachment的contentBytes字段是base64编码的字符串;
  • 你的代码中直接将byte[]类型赋值给FileAttachment.ContentBytes,Newtonsoft.Json默认会把byte[]序列化为数字数组(如[0, 12, 34...]),导致Graph无法解析数字值为预期的引号包裹字符串。

另外你推测的邮件正文内容类型问题,确实也可能存在隐患:BodyType.Text枚举序列化后会输出数字0,同样可能触发解析异常。

解决方法

方法1:手动转换为base64字符串并使用匿名类构建请求体

避开Microsoft Graph实体类的序列化问题,直接用匿名类构建符合API要求的结构:

byte[] contentBytes = System.IO.File.ReadAllBytes(@"C:\Users\user\Downloads\test\test.png");
// 将字节数组转为base64字符串
string base64Content = Convert.ToBase64String(contentBytes);

// 构建符合API格式的附件对象
var attachment = new
{
    odataType = "#microsoft.graph.fileAttachment",
    contentBytes = base64Content,
    contentType = "image/png",
    contentId = "testing",
    name = "testing.png"
};

// 构建邮件消息
var message = new
{
    Subject = emailSubject,
    Body = new
    {
        ContentType = "Text", // 直接用字符串替代枚举,避免数字序列化
        Content = emailBody
    },
    Attachments = new[] { attachment },
    ToRecipients = new[] { new { EmailAddress = new { Address = toEmail, Name = toName } } },
    BccRecipients = new object[] { } // 用空数组替代空List
};

var body = JsonConvert.SerializeObject(new { message = message });

方法2:配置Newtonsoft.Json序列化规则(保留实体类)

如果坚持使用Microsoft Graph的实体类,可通过序列化配置让byte[]转为base64字符串:

// 配置序列化规则
var jsonSettings = new JsonSerializerSettings
{
    Converters = new List<JsonConverter> { new ByteArrayConverter() } // 自动将byte[]转为base64
};

var body = JsonConvert.SerializeObject(new { message = message }, jsonSettings);

同时将正文的ContentType改为字符串赋值:

Body = new ItemBody
{
    ContentType = (BodyType)Enum.Parse(typeof(BodyType), "Text"),
    Content = emailBody
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 11:01:33