问题描述
|
我正在尝试从电子邮件的附件中获取内容。我能够阅读电子邮件及其所有属性。附件是一个文本文件(.txt)。我将如何获取附件的实际文本内容?以下是我的代码部分,显示了我如何抓取每封电子邮件,然后获取其属性并将其存储在findResults列表中。诸如fileAttachment.Name之类的东西会给我附件的名称。 fileAttachment.content.tostring()只会显示system.Byte []。
FindItemsResults<Item> findResults = service.FindItems(fid1,new ItemView(int.MaxValue));
service.LoadPropertiesForItems(from Item item in findResults select item,PropertySet.FirstClassproperties);
foreach (Item item in findResults)
{
String body = \"\";
#region attachments
if (ReadAttachments == \"1\")
{
EmailMessage message = EmailMessage.Bind(service,item.Id,new PropertySet(BasePropertySet.IdOnly,ItemSchema.Attachments));
foreach (Attachment attachment in message.Attachments)
{
if (attachment is FileAttachment)
{
FileAttachment fileAttachment = attachment as FileAttachment;
// Load the file attachment into memory and print out its file name.
fileAttachment.Load();
String attachbody = fileAttachment.Content.ToString();
if (attachbody.Length > 8000)
{
attachbody = attachbody.Substring(0,8000);
}
Console.writeline(attachbody);
#endregion
}
}
}
#endregion
}
解决方法
那是因为它是一个字节数组,您必须使用StreamReader来获取它
var stream = new System.IO.MemoryStream(fileAttachment.Content);
var reader = new System.IO.StreamReader(stream,UTF8Encoding.UTF8);
var text = reader.ReadToEnd();