如何为Microsoft Graph发送的邮件添加附件?遇Badrequest错误
Microsoft Graph添加附件发送邮件报BadRequest错误,Attachment类无ContentBytes属性
使用Microsoft Graph开发邮件发送功能,无附件时可正常发送,但添加附件后触发BadRequest错误。当前使用Microsoft.Graph.Models.Attachment类,该类没有ContentBytes属性,尝试通过AdditionalData字典添加contentBytes字段,问题仍未解决。
原始代码:
var emailMessage = new { message = new { subject = messageSubject, body = new { contentType = "Text", content = messageBody }, toRecipients = new[] { new { emailAddress = new { address = userEmail } } }, Attachments = new List<Attachment> { new Attachment { OdataType = "#microsoft.graph.fileAttachment", Name = "TextFile1.txt", ContentType = "text/plain", }, }, } }; // Convert the email message to a JSON string and send the email via Microsoft Graph var jsonMessage = JsonConvert.SerializeObject(emailMessage); var response = await httpClient.PostAsync($"{graphApiEndpoint}/users/{userEmail}/sendMail", new StringContent(jsonMessage, System.Text.Encoding.UTF8, "application/json")); if (response.IsSuccessStatusCode) { Console.WriteLine("Email sent successfully."); } else { Console.WriteLine("Failed to send email. Status code: " + response.StatusCode); }
尝试过的代码:
Attachment = new Microsoft.Graph.Models.Attachment { OdataType = "#microsoft.graph.fileAttachment", Name = "TextFile1.txt", ContentType = "text/plain", AdditionalData = new Dictionary<string,object> { { "contentBytes", contentBytes } } },
解决方案
1. 核心问题:误用基类Attachment而非派生类FileAttachment
Attachment是所有附件类型的基类,文件附件需使用**FileAttachment**派生类,该类原生包含ContentBytes属性,无需通过AdditionalData手动添加字段。基类Attachment无此属性,即使强行添加字段,序列化后的JSON格式也不符合Graph API要求,触发BadRequest。
2. 修正代码示例
替换Attachment为FileAttachment,直接赋值ContentBytes(需将文件字节数组转换为Base64字符串):
// 将文件字节数组转换为Base64字符串 string base64Content = Convert.ToBase64String(contentBytes); var emailMessage = new { message = new { subject = messageSubject, body = new { contentType = "Text", content = messageBody }, toRecipients = new[] { new { emailAddress = new { address = userEmail } } }, attachments = new List<FileAttachment> // 替换为FileAttachment列表 { new FileAttachment { OdataType = "#microsoft.graph.fileAttachment", Name = "TextFile1.txt", ContentType = "text/plain", ContentBytes = base64Content // 使用原生属性赋值 } } } }; // 后续请求代码不变,建议添加错误详情打印 var jsonMessage = JsonConvert.SerializeObject(emailMessage); var response = await httpClient.PostAsync($"{graphApiEndpoint}/users/{userEmail}/sendMail", new StringContent(jsonMessage, System.Text.Encoding.UTF8, "application/json")); if (response.IsSuccessStatusCode) { Console.WriteLine("Email sent successfully."); } else { // 打印详细错误信息,便于排查 string errorDetails = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Failed to send email. Status code: {response.StatusCode}, Error: {errorDetails}"); }
3. 额外检查点
- Base64转换:确保文件字节数组正确转换为Base64字符串,避免编码错误。
- API权限:确认应用已授予
Mail.Send权限(委托或应用权限),且权限已完成同意流程。 - 序列化配置:使用Newtonsoft.Json时,保持默认配置即可,无需额外修改以保证
OdataType等属性正常序列化。 - 错误详情:请求失败时读取响应内容,Graph API会返回具体错误原因(如字段缺失、格式错误),可快速定位问题。
内容的提问来源于stack exchange,提问作者Knarf
相关产品推荐
相关产品推荐

