如何通过EWS读取邮件BodyText?C#代码报错求助
问题解决方案
错误1:必须先加载或赋值属性才能读取(第44行)
原因
FindItems方法默认仅返回邮件基础属性(如Subject、ItemId),TextBody不在默认返回列表中;当前代码仅对EmailMessage类型调用Load(),其他类型Item未加载属性,且即使是EmailMessage,TextBody的读取也不在Load()后的代码块内,导致读取未加载的属性。
解决方法
- 使用
PropertySet指定需要获取的属性,一次性加载所需字段,避免逐个调用Load(),提升效率; - 统一处理所有Item类型的属性加载,确保读取
TextBody前属性已加载完成。
错误2:未将对象引用设置到对象的实例(第34行,偶发)
原因
ExchangeService的Credentials格式错误,需传入完整邮箱地址而非仅域名;- 网络波动导致
FindItems请求失败,返回null; - 未捕获服务初始化或请求时的异常,导致service实例或请求结果为null。
解决方法
- 确保Credentials传入完整邮箱地址(如
user@mail.com); - 对
service.FindItems的返回结果做null检查; - 增加异常捕获,处理网络、认证类异常。
修改后的完整代码
ExchangeService service = new ExchangeService(); // 注意:Credentials需传入完整邮箱地址 service.Credentials = new WebCredentials("your-full-email@mail.com", "your-password"); service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx"); List<string> items = new List<string>(); ItemView view = new ItemView(50); // 指定需要加载的属性,包含TextBody,避免重复调用Load PropertySet propertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.TextBody); view.PropertySet = propertySet; FindItemsResults<Item> findResults = null; try { findResults = service.FindItems(WellKnownFolderName.Inbox, view); } catch (Exception ex) { Console.WriteLine($"获取邮件列表失败:{ex.Message}"); return; } // 检查结果是否为空 if (findResults == null || !findResults.Any()) { Console.WriteLine("未找到邮件"); return; } foreach (Item item in findResults) { if (!string.IsNullOrEmpty(item.TextBody)) { items.Add(item.TextBody); Console.WriteLine($"主题:{item.Subject}"); Console.WriteLine($"内容:{item.TextBody}\n"); } }
额外说明
- 若需获取HTML格式的邮件内容,可将
ItemSchema.TextBody替换为ItemSchema.Body,通过item.Body.Text读取; - 若要获取邮箱内所有邮件,需处理分页逻辑:通过
findResults.MoreAvailable判断是否还有未获取的邮件,循环调整ItemView的Offset参数继续获取。
内容的提问来源于stack exchange,提问作者Frederico Eglesias
相关产品推荐
相关产品推荐

