Microsoft Graph 5.15发送大附件邮件代码报错求助
Microsoft Graph 5.15 大附件邮件发送代码修复
针对你遇到的两个API调用问题,本质是Microsoft Graph SDK v5与旧版本(如v4)的语法差异,以下是具体修复方案:
1. 修复 Send 方法调用失败问题
在Graph SDK v5中,发送邮件的接口已简化,无需链式调用 .Request().PostAsync(),直接调用 SendAsync() 即可:
原错误代码:
await _thisGraphClient.Users[userId].Messages[savedDraft.Id].Send().Request().PostAsync();
修复后:
await _thisGraphClient.Users[userId].Messages[savedDraft.Id].SendAsync();
2. 修复 CreateUploadSession 方法调用失败问题
v5中创建附件上传会话的接口结构发生变化,需通过 CreateUploadSession.PostAsync() 传递 CreateAttachmentUploadSessionPostRequestBody 对象,而非直接传入 AttachmentItem:
原错误代码:
var uploadSession = await _thisGraphClient.Users[userId] .Messages[savedDraft.Id] .Attachments .CreateUploadSession(new AttachmentItem { AttachmentType = AttachmentType.File, Name = largeAttachment.Name, Size = fileStream.Length, ContentType = "application/octet-stream" }) .Request() .PostAsync();
修复后:
var uploadSession = await _thisGraphClient.Users[userId] .Messages[savedDraft.Id] .Attachments .CreateUploadSession .PostAsync(new CreateAttachmentUploadSessionPostRequestBody { AttachmentItem = new AttachmentItem { AttachmentType = AttachmentType.File, Name = largeAttachment.Name, Size = fileStream.Length, ContentType = "application/octet-stream" } });
完整修复后的代码片段
var savedDraft = await _graphClient.Users[userId].Messages.PostAsync(draftMessage); // Handle large attachments foreach (var largeAttachment in largeAttachments) { var fileStream = File.OpenRead(largeAttachment.FullName); var uploadSession = await _thisGraphClient.Users[userId] .Messages[savedDraft.Id] .Attachments .CreateUploadSession .PostAsync(new CreateAttachmentUploadSessionPostRequestBody { AttachmentItem = new AttachmentItem { AttachmentType = AttachmentType.File, Name = largeAttachment.Name, Size = fileStream.Length, ContentType = "application/octet-stream" } }); int maxSliceSize = 320 * 1024; // 320 KB - Change this to fit your needs var fileUploadTask = new LargeFileUploadTask<FileAttachment>(uploadSession, fileStream, maxSliceSize); var totalLength = fileStream.Length; IProgress<long> progress = new Progress<long>(prog => { Console.WriteLine($"Uploaded {prog} bytes of {totalLength} bytes"); }); try { var uploadResult = await fileUploadTask.UploadAsync(progress); Console.WriteLine(uploadResult.UploadSucceeded ? "Upload complete" : "Upload failed"); } catch (ServiceException ex) { Console.WriteLine($"Error uploading: {ex.ToString()}"); } finally { // 释放文件流,避免资源泄漏 fileStream.Dispose(); } } // Send the draft await _thisGraphClient.Users[userId].Messages[savedDraft.Id].SendAsync();
内容的提问来源于stack exchange,提问作者CDVS
相关产品推荐
相关产品推荐

