在 PST 文件中管理邮件
获取 Outlook PST 文件中的邮件信息
在 读取 PST 文件并检索信息 文章中我们讨论了如何加载 Outlook PST 文件并浏览其文件夹以获取文件夹名称和其中的邮件数量。本文解释了如何读取 PST 文件中的所有文件夹和子文件夹并显示邮件信息,例如主题、发件人和收件人。Outlook PST 文件可能包含嵌套文件夹。要从这些文件夹以及顶层文件夹获取邮件信息,请使用递归方法读取所有文件夹。以下代码片段展示了如何递归读取 Outlook PST 文件并显示文件夹和邮件内容。
public static void Run()
{
string dataDir = RunExamples.GetDataDir_Outlook();
// Load the Outlook file
string path = dataDir + "PersonalStorage.pst";
try
{
// Load the Outlook PST file
PersonalStorage personalStorage = PersonalStorage.FromFile(path);
// Get the Display Format of the PST file
Console.WriteLine("Display Format: " + personalStorage.Format);
// Get the folders and messages information
FolderInfo folderInfo = personalStorage.RootFolder;
// Call the recursive method to display the folder contents
DisplayFolderContents(folderInfo, personalStorage);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
/// <summary>
/// This is a recursive method to display contents of a folder
/// </summary>
/// <param name="folderInfo"></param>
/// <param name="pst"></param>
private static void DisplayFolderContents(FolderInfo folderInfo, PersonalStorage pst)
{
// Display the folder name
Console.WriteLine("Folder: " + folderInfo.DisplayName);
Console.WriteLine("==================================");
// Display information about messages inside this folder
MessageInfoCollection messageInfoCollection = folderInfo.GetContents();
foreach (MessageInfo messageInfo in messageInfoCollection)
{
Console.WriteLine("Subject: " + messageInfo.Subject);
Console.WriteLine("Sender: " + messageInfo.SenderRepresentativeName);
Console.WriteLine("Recipients: " + messageInfo.DisplayTo);
Console.WriteLine("------------------------------");
}
// Call this method recursively for each subfolder
if (folderInfo.HasSubFolders == true)
{
foreach (FolderInfo subfolderInfo in folderInfo.GetSubFolders())
{
DisplayFolderContents(subfolderInfo, pst);
}
}
}
从 PST 文件中提取邮件
本文展示了如何读取 Microsoft Outlook PST 文件并提取邮件。随后将邮件以 MSG 格式保存到磁盘。
Try it out!
运行 ConversationThread 简单的应用项目,探索 Aspose.Email 功能的有趣用法,以从 PST 中读取邮件并查找会话线程。
下面的代码片段展示了如何从 PST 文件中提取邮件:
- 使用递归方法遍历所有文件夹(包括任何嵌套文件夹),并调用 PersonalStorage.ExtractMessage() 方法将 Outlook 邮件获取到一个实例中 MapiMessage 类。
- 之后,调用 MapiMessage.Save() 方法将邮件以 MSG 格式保存到磁盘或流中。
public static void Run()
{
// The path to the file directory.
string dataDir = RunExamples.GetDataDir_Outlook();
// Load the Outlook file
string path = dataDir + "PersonalStorage.pst";
try
{
// load the Outlook PST file
PersonalStorage pst = PersonalStorage.FromFile(path);
// get the Display Format of the PST file
Console.WriteLine("Display Format: " + pst.Format);
// get the folders and messages information
FolderInfo folderInfo = pst.RootFolder;
// Call the recursive method to extract msg files from each folder
ExtractMsgFiles(folderInfo, pst);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
/// <summary>
/// This is a recursive method to display contents of a folder
/// </summary>
/// <param name="folderInfo"></param>
/// <param name="pst"></param>
private static void ExtractMsgFiles(FolderInfo folderInfo, PersonalStorage pst)
{
// display the folder name
Console.WriteLine("Folder: " + folderInfo.DisplayName);
Console.WriteLine("==================================");
// loop through all the messages in this folder
MessageInfoCollection messageInfoCollection = folderInfo.GetContents();
foreach (MessageInfo messageInfo in messageInfoCollection)
{
Console.WriteLine("Saving message {0} ....", messageInfo.Subject);
// get the message in MapiMessage instance
MapiMessage message = pst.ExtractMessage(messageInfo);
// save this message to disk in msg format
message.Save(message.Subject.Replace(":", " ") + ".msg");
// save this message to stream in msg format
MemoryStream messageStream = new MemoryStream();
message.Save(messageStream);
}
// Call this method recursively for each subfolder
if (folderInfo.HasSubFolders == true)
{
foreach (FolderInfo subfolderInfo in folderInfo.GetSubFolders())
{
ExtractMsgFiles(subfolderInfo, pst);
}
}
}
识别 MAPI 项类型
该 MapiItemType 枚举表示一种 MAPI 项类型,可显式转换为从以下基类派生的对应类对象 IMapiMessageItem 接口。这样用户可以避免检查 MessageClass 属性值在邮件转换之前。
以下代码示例展示了如何为要转换的项定义类型:
foreach (var messageInfo in folder.EnumerateMessages())
{
var msg = pst.ExtractMessage(messageInfo);
switch (msg.SupportedType)
{
// Non-supported type. MapiMessage cannot be converted to an appropriate item type.
// Just use in MSG format.
case MapiItemType.None:
break;
// An email message. Conversion isn't required.
case MapiItemType.Message:
break;
// A contact item. Can be converted to MapiContact.
case MapiItemType.Contact:
var contact = (MapiContact)msg.ToMapiMessageItem();
break;
// A calendar item. Can be converted to MapiCalendar.
case MapiItemType.Calendar:
var calendar = (MapiCalendar)msg.ToMapiMessageItem();
break;
// A distribution list. Can be converted to MapiDistributionList.
case MapiItemType.DistList:
var dl = (MapiDistributionList)msg.ToMapiMessageItem();
break;
// A Journal entry. Can be converted to MapiJournal.
case MapiItemType.Journal:
var journal = (MapiJournal)msg.ToMapiMessageItem();
break;
// A StickyNote. Can be converted to MapiNote.
case MapiItemType.Note:
var note = (MapiNote)msg.ToMapiMessageItem();
break;
// A Task item. Can be converted to MapiTask.
case MapiItemType.Task:
var task = (MapiTask)msg.ToMapiMessageItem();
break;
}
}
邮件搜索与检索
Aspose.Email 提供以下重载方法: FolderInfo 用于过滤和检索邮件的类:
- IEnumerable
EnumerateMessages(MailQuery mailQuery) - 使用 MailQuery 过滤邮件。 - IEnumerable
EnumerateMessages(MessageKind kind) - 按类型(MessageKind)检索消息。 - IEnumerable
EnumerateMessages(int startIndex, int count) - 使用起始索引和计数进行消息检索分页。
分页检索文件夹内容
在处理大型 PST 文件夹时,一次性检索所有邮件可能效率低下。为提升性能和可控性,Aspose.Email for .NET 在 FolderInfo.GetContents 方法。此方法检索符合指定查询的邮件子集,起始于给定索引并受计数限制。这使您能够以更小、更易管理的批次获取邮件。该方法接受以下参数:
IList<MessageInfo> FolderInfo.GetContents(MailQuery query, int startIndex, int count)
-
query — 要应用于邮件的过滤器(可选)
-
startIndex — 开始检索的零基索引
-
count — 要返回的邮件数量
下面的代码示例演示如何在项目中实现此方法:
// Load the PST file
using (var pst = PersonalStorage.FromFile(fileName))
{
// Access a specific subfolder
var folder = pst.RootFolder.GetSubFolder("Inbox");
// Build a query to filter messages by sender address
var queryBuilder = new PersonalStorageQueryBuilder();
queryBuilder.From.Contains("report-service", true);
// Define the page size
int pageSize = 5;
// Retrieve and process messages in pages
for (int pageIndex = 0; pageIndex < 6; pageIndex++)
{
int startIndex = pageIndex * pageSize;
// Get a page of messages
var messages = folder.GetContents(queryBuilder.GetQuery(), startIndex, pageSize);
foreach (MessageInfo messageInfo in messages)
{
// Output basic info about each message
Console.WriteLine($"Subject: {messageInfo.Subject}, Sender: {messageInfo.SenderRepresentativeName}");
}
}
}
直接从 PST 保存邮件到流
要将 PST 文件中的邮件直接保存到流中,而不提取邮件的 MsgInfo,请使用 SaveMessageToStream() 方法。下面的代码片段展示了如何直接从 PST 将邮件保存到流。
// The path to the file directory.
string dataDir = RunExamples.GetDataDir_Outlook();
// Load the Outlook file
string path = dataDir + "PersonalStorage.pst";
// Save message to MemoryStream
using (PersonalStorage personalStorage = PersonalStorage.FromFile(path))
{
FolderInfo inbox = personalStorage.RootFolder.GetSubFolder("Inbox");
foreach (MessageInfo messageInfo in inbox.EnumerateMessages())
{
using (MemoryStream memoryStream = new MemoryStream())
{
personalStorage.SaveMessageToStream(messageInfo.EntryIdString, memoryStream);
}
}
}
// Save message to file
using (PersonalStorage pst = PersonalStorage.FromFile(path))
{
FolderInfo inbox = pst.RootFolder.GetSubFolder("Inbox");
foreach (MessageInfo messageInfo in inbox.EnumerateMessages())
{
using (FileStream fs = File.OpenWrite(messageInfo.Subject + ".msg"))
{
pst.SaveMessageToStream(messageInfo.EntryIdString, fs);
}
}
}
using (PersonalStorage pst = PersonalStorage.FromFile(path))
{
FolderInfo inbox = pst.RootFolder.GetSubFolder("Inbox");
// To enumerate entryId of messages you may use FolderInfo.EnumerateMessagesEntryId() method:
foreach (string entryId in inbox.EnumerateMessagesEntryId())
{
using (MemoryStream ms = new MemoryStream())
{
pst.SaveMessageToStream(entryId, ms);
}
}
}
提取特定数量的邮件
以下代码片段展示了如何从 PST 中提取指定数量的邮件。只需提供第一封邮件的索引以及要提取的邮件总数。
FolderInfo inbox = personalStorage.RootFolder.GetSubFolder("Inbox");
// Extracts messages starting from 10th index top and extract total 100 messages
MessageInfoCollection messages = inbox.GetContents(10, 100);
获取 PST 中的总项目计数
Aspose.Email 提供了 GetTotalItemsCount() 方法的 PersonalStorage.Store 属性。它返回 PST 中包含的邮件项目总数。
以下代码示例展示了如何检索存储在 PST 文件中的项目总数(邮件、约会、联系人等):
using (var pst = PersonalStorage.FromFile("my.pst", false))
{
var count = pst.Store.GetTotalItemsCount();
}
在不提取完整邮件的情况下提取附件
Aspose.Email API 可用于在不先提取完整邮件的情况下从 PST 消息中提取附件。 ExtractAttachments 方法的 PersonalStorage 可用于实现此功能。下面的代码片段展示了如何在不提取完整邮件的情况下提取附件。
string dataDir = RunExamples.GetDataDir_Outlook();
using (PersonalStorage personalstorage = PersonalStorage.FromFile(dataDir + "Outlook.pst"))
{
FolderInfo folder = personalstorage.RootFolder.GetSubFolder("Inbox");
foreach (var messageInfo in folder.EnumerateMessagesEntryId())
{
MapiAttachmentCollection attachments = personalstorage.ExtractAttachments(messageInfo);
if (attachments.Count != 0)
{
foreach (var attachment in attachments)
{
if (!string.IsNullOrEmpty(attachment.LongFileName))
{
if (attachment.LongFileName.Contains(".msg"))
{
continue;
}
else
{
attachment.Save(dataDir + @"\Attachments\" + attachment.LongFileName);
}
}
}
}
}
}
从 PST 文件中提取邮件收件人
可以使用消息条目 ID 从 PST 文件中提取邮件收件人。此功能在 PersonalStorage class。下面的代码示例演示如何提取邮件收件人:
通过 EntryId(使用 ExtractRecipients(string entryId) 方法的 PersonalStorage class)
using (var pst = PersonalStorage.FromFile(fileName))
{
// Recipients are extracted using the entry ID
var recipients = pst.ExtractRecipients("AAAAADzSMygQQFJOkKwVhb8v5EUkASAA");
}
来自 MessageInfo(使用 MapiRecipientCollection ExtractRecipients(MessageInfo messageInfo) method)
using (var pst = PersonalStorage.FromFile(fileName))
{
// The "Inbox" folder is obtained
var folder = pst.RootFolder.GetSubFolder("Inbox");
// Each message in the "Inbox" folder is iterated
foreach (var messageInfo in folder.EnumerateMessages())
{
// Recipients are extracted from each message
var recipients = pst.ExtractRecipients(messageInfo);
}
}
搜索邮件和文件夹
按条件搜索
个人存储 (PST) 文件可能包含海量数据。在如此大的文件中搜索符合特定条件的数据,需要在代码中加入多个检查点来过滤信息。使用 PersonalStorageQueryBuilder 类,Aspose.Email 使得可以根据指定的搜索条件在 PST 中搜索特定记录。可以根据发送者、接收者、主题、邮件重要性、是否有附件、邮件大小,甚至邮件 ID 等搜索参数来搜索 PST 中的邮件。 PersonalStorageQueryBuilder 也可用于搜索子文件夹。
在 PST 中搜索邮件和文件夹
下面的代码片段展示了如何使用 PersonalStorageQueryBuilder 类,用于基于不同搜索条件在 PST 中搜索内容。例如,展示了基于以下条件搜索 PST:
- 邮件重要性。
- 邮件类别。
- 是否有附件。
- 邮件大小。
- 未读邮件。
- 带附件的未读邮件,以及
- 具有特定子文件夹名称的文件夹。
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Outlook();
using (PersonalStorage personalStorage = PersonalStorage.FromFile(dataDir + "Outlook.pst"))
{
FolderInfo folder = personalStorage.RootFolder.GetSubFolder("Inbox");
PersonalStorageQueryBuilder builder = new PersonalStorageQueryBuilder();
// High importance messages
builder.Importance.Equals((int)MapiImportance.High);
MessageInfoCollection messages = folder.GetContents(builder.GetQuery());
Console.WriteLine("Messages with High Imp:" + messages.Count);
builder = new PersonalStorageQueryBuilder();
builder.MessageClass.Equals("IPM.Note");
messages = folder.GetContents(builder.GetQuery());
Console.WriteLine("Messages with IPM.Note:" + messages.Count);
builder = new PersonalStorageQueryBuilder();
// Messages with attachments AND high importance
builder.Importance.Equals((int)MapiImportance.High);
builder.HasFlags(MapiMessageFlags.MSGFLAG_HASATTACH);
messages = folder.GetContents(builder.GetQuery());
Console.WriteLine("Messages with atts: " + messages.Count);
builder = new PersonalStorageQueryBuilder();
// Messages with size > 15 KB
builder.MessageSize.Greater(15000);
messages = folder.GetContents(builder.GetQuery());
Console.WriteLine("messages size > 15Kb:" + messages.Count);
builder = new PersonalStorageQueryBuilder();
// Unread messages
builder.HasNoFlags(MapiMessageFlags.MSGFLAG_READ);
messages = folder.GetContents(builder.GetQuery());
Console.WriteLine("Unread:" + messages.Count);
builder = new PersonalStorageQueryBuilder();
// Unread messages with attachments
builder.HasNoFlags(MapiMessageFlags.MSGFLAG_READ);
builder.HasFlags(MapiMessageFlags.MSGFLAG_HASATTACH);
messages = folder.GetContents(builder.GetQuery());
Console.WriteLine("Unread msgs with atts: " + messages.Count);
// Folder with name of 'SubInbox'
builder = new PersonalStorageQueryBuilder();
builder.FolderName.Equals("SubInbox");
FolderInfoCollection folders = folder.GetSubFolders(builder.GetQuery());
Console.WriteLine("Folder having subfolder: " + folders.Count);
builder = new PersonalStorageQueryBuilder();
// Folders with subfolders
builder.HasSubfolders();
folders = folder.GetSubFolders(builder.GetQuery());
Console.WriteLine(folders.Count);
}
忽略大小写参数搜索
以下代码片段展示了如何在 PST 中使用忽略大小写参数搜索字符串。
using (PersonalStorage personalStorage = PersonalStorage.Create("CaseSensitivity.pst", FileFormatVersion.Unicode))
{
FolderInfo folderinfo = personalStorage.CreatePredefinedFolder("Inbox", StandardIpmFolder.Inbox);
folderinfo.AddMessage(MapiMessage.FromMailMessage(MailMessage.Load("Sample.eml")));
PersonalStorageQueryBuilder builder = new PersonalStorageQueryBuilder();
// IgnoreCase is True
builder.From.Contains("automated", true);
MailQuery query = builder.GetQuery();
MessageInfoCollection coll = folderinfo.GetContents(query);
Console.WriteLine(coll.Count);
}
通过多个关键字搜索邮件主题
您可以使用 MailQueryBuilder.Or 方法,用于查找主题中包含至少一个指定词的邮件,如下所示:
var builder1 = new PersonalStorageQueryBuilder();
builder1.Subject.Contains("Review"); // 'Review' is key word for the search
var builder2 = new PersonalStorageQueryBuilder();
builder2.Subject.Contains("Error"); // 'Error' is also key word for the search
var queryBuilder = new PersonalStorageQueryBuilder();
queryBuilder.Or(builder1.GetQuery(), builder2.GetQuery()); // message subjects must contain 'Review' or 'Error' words
using (var storage = PersonalStorage.FromFile("example.pst"))
{
var folderInfo = storage.RootFolder.GetSubFolder("Inbox");
var messageInfos = folderInfo.GetContents(queryBuilder.GetQuery());
foreach (var messageInfo in messageInfos)
{
Console.WriteLine(messageInfo.Subject);
}
}
操作消息
将项目移动到其他文件夹
Aspose.Email 使得可以将项目从源文件夹移动到同一个人存储 (PST) 文件的另一个文件夹。包括:
- 将指定的文件夹移动到新父文件夹。
- 将指定的消息移动到新文件夹。
- 将内容移动到新文件夹。
- 将子文件夹移动到新父文件夹。
以下代码片段展示了如何将消息和文件夹等项目从源文件夹移动到同一 PST 文件中的另一个文件夹。
using(PersonalStorage personalStorage = PersonalStorage.FromFile("test.pst"))
{
FolderInfo inbox = personalStorage.GetPredefinedFolder(StandardIpmFolder.Inbox);
FolderInfo deleted = personalStorage.GetPredefinedFolder(StandardIpmFolder.DeletedItems);
FolderInfo subfolder = inbox.GetSubFolder("Subfolder");
// Move folder and message to the Deleted Items
personalStorage.MoveItem(subfolder, deleted);
MessageInfoCollection contents = subfolder.GetContents();
personalStorage.MoveItem(contents[0], deleted);
// Move all inbox subfolders and subfolder contents to the Deleted Items
inbox.MoveSubfolders(deleted);
subfolder.MoveContents(deleted);
}
更新消息属性
有时需要更新消息的某些属性,例如更改主题、标记重要性等。使用以下方式可在 PST 文件中更新这些属性。 FolderInfo.ChangeMessages 方法。本文展示了如何在 PST 文件中批量更新消息的属性。以下代码片段演示了如何对 PST 文件中的多条消息批量更新属性。
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Outlook() + "Sub.pst";
// Load the Outlook PST file
PersonalStorage personalStorage = PersonalStorage.FromFile(dataDir);
// Get the required subfolder
FolderInfo inbox = personalStorage.RootFolder.GetSubFolder("Inbox");
// find messages having From = "someuser@domain.com"
PersonalStorageQueryBuilder queryBuilder = new PersonalStorageQueryBuilder();
queryBuilder.From.Contains("someuser@domain.com");
// Get Contents from Query
MessageInfoCollection messages = inbox.GetContents(queryBuilder.GetQuery());
// Save (MessageInfo,EntryIdString) in List
IList<string> changeList = new List<string>();
foreach (MessageInfo messageInfo in messages)
{
changeList.Add(messageInfo.EntryIdString);
}
// Compose the new properties
MapiPropertyCollection updatedProperties = new MapiPropertyCollection();
updatedProperties.Add(MapiPropertyTag.PR_SUBJECT_W, new MapiProperty(MapiPropertyTag.PR_SUBJECT_W, Encoding.Unicode.GetBytes("New Subject")));
updatedProperties.Add(MapiPropertyTag.PR_IMPORTANCE, new MapiProperty(MapiPropertyTag.PR_IMPORTANCE, BitConverter.GetBytes((long)2)));
// update messages having From = "someuser@domain.com" with new properties
inbox.ChangeMessages(changeList, updatedProperties);
更新自定义属性
有时需要标记在 PST 文件中已处理的项目。Aspose.Email API 通过 MapiProperty 和 MapiNamedProperty 实现此功能。以下方法在实现此目的时很有帮助。
- ctor MapiNamedProperty(long propertyTag, string nameIdentifier, Guid propertyGuid, byte[] propertyValue)
- ctor MapiNamedProperty(long propertyTag, long nameIdentifier, Guid propertyGuid, byte[] propertyValue)
- FolderInfo.ChangeMessages(MapiPropertyCollection updatedProperties) - 更改文件夹中所有消息
- PersonalStorage.ChangeMessage(string entryId, MapiPropertyCollection updatedProperties) - 更改消息属性
public static void Run()
{
// Load the Outlook file
string dataDir = RunExamples.GetDataDir_Outlook() + "Sub.pst";
using (PersonalStorage personalStorage = PersonalStorage.FromFile(dataDir))
{
FolderInfo testFolder = personalStorage.RootFolder.GetSubFolder("Inbox");
// Create the collection of message properties for adding or updating
MapiPropertyCollection newProperties = new MapiPropertyCollection();
// Normal, Custom and PidLidLogFlags named property
MapiProperty property = new MapiProperty(MapiPropertyTag.PR_ORG_EMAIL_ADDR_W,Encoding.Unicode.GetBytes("test_address@org.com"));
MapiProperty namedProperty1 = new MapiNamedProperty(GenerateNamedPropertyTag(0, MapiPropertyType.PT_LONG),"ITEM_ID",Guid.NewGuid(),BitConverter.GetBytes(123));
MapiProperty namedProperty2 = new MapiNamedProperty(GenerateNamedPropertyTag(1, MapiPropertyType.PT_LONG),0x0000870C,new Guid("0006200A-0000-0000-C000-000000000046"),BitConverter.GetBytes(0));
newProperties.Add(namedProperty1.Tag, namedProperty1);
newProperties.Add(namedProperty2.Tag, namedProperty2);
newProperties.Add(property.Tag, property);
testFolder.ChangeMessages(testFolder.EnumerateMessagesEntryId(), newProperties);
}
}
private static long GenerateNamedPropertyTag(long index, MapiPropertyType dataType)
{
return (((0x8000 | index) << 16) | (long)dataType) & 0x00000000FFFFFFFF;
}
删除消息
本文展示了如何使用 FolderInfo 类,用于访问 PST 文件中的特定文件夹。要删除先前加载或创建的 PST 文件中已发送子文件夹的邮件:
- 创建该类的实例 FolderInfo 类并加载已发送子文件夹的内容。
- 通过调用 FolderInfo.DeleteChildItem() 方法并传递 MessageInfo.EntryId 作为参数。以下代码片段展示了如何删除 PST 文件中已发送子文件夹的邮件。
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Outlook() + "Sub.pst";
// Load the Outlook PST file
PersonalStorage personalStorage = PersonalStorage.FromFile(dataDir);
// Get the Sent items folder
FolderInfo folderInfo = personalStorage.GetPredefinedFolder(StandardIpmFolder.SentItems);
MessageInfoCollection msgInfoColl = folderInfo.GetContents();
foreach (MessageInfo msgInfo in msgInfoColl)
{
Console.WriteLine(msgInfo.Subject + ": " + msgInfo.EntryIdString);
if (msgInfo.Subject.Equals("some delete condition") == true)
{
// Delete this item
folderInfo.DeleteChildItem(msgInfo.EntryId);
Console.WriteLine("Deleted this message");
}
}
删除文件夹
您可以通过将 PST 文件夹移动到“已删除邮件”文件夹来删除它。
using (PersonalStorage pst = PersonalStorage.FromFile(@"test.pst"))
{
FolderInfo deletedItemsFolder = pst.GetPredefinedFolder(StandardIpmFolder.DeletedItems);
FolderInfo emptyFolder = pst.RootFolder.GetSubFolder("Empty folder");
FolderInfo someFolder = pst.RootFolder.GetSubFolder("Some folder");
pst.MoveItem(emptyFolder, deletedItemsFolder);
pst.MoveItem(someFolder, deletedItemsFolder);
}
此方法的优势在于已删除的文件夹可以轻松恢复。
FolderInfo someFolder = deletedItemsFolder.GetSubFolder("Some folder");
pst.MoveItem(someFolder, pst.RootFolder);
如果需要,您也可以永久从“已删除邮件”文件夹中移除文件夹。
deletedItemsFolder.DeleteChildItem(emptyFolder.EntryId);
该 DeleteChildItem() 如果您想立即且永久删除子文件夹,而不经过已删除项目文件夹,可对任何文件夹使用此方法。
FolderInfo someFolder = pst.RootFolder.GetSubFolder("Some folder");
pst.RootFolder.DeleteChildItem(someFolder.EntryId);
从 PST 删除项目
通过调用 DeleteItem(string entryId) 方法,使用与项目关联的唯一 entryId 从个人存储表 (PST) 中删除项目(文件夹或消息) PersonalStorage 类。
以下代码片段可用于调用 DeleteItem 方法并将 entryId 作为参数传递:
var pst = PersonalStorage.FromFile("sample.pst");
// ...
pst.DeleteItem(entryId);
// ...
请注意:
- 此方法将永久删除 PST 中的项目,且无法撤销。使用此方法时请谨慎,以避免意外数据丢失。
- 按照标准约定,确保 entryId 有效且对应 PST 中的现有项目。
- 否则,将抛出异常。建议对 PST 进行备份或在需要时实施适当的措施以恢复已删除的项目。
批量删除
Aspose.Email API 可用于批量删除 PST 文件中的项目。这通过使用 DeleteChildItems() 方法接受一个指向待删除项目的条目 ID 列表。以下代码片段展示了如何批量删除 PST 文件中的项目。
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Outlook() + @"Sub.pst";
using (PersonalStorage personalStorage = PersonalStorage.FromFile(dataDir))
{
// Get Inbox SubFolder from Outlook file
FolderInfo inbox = personalStorage.RootFolder.GetSubFolder("Inbox");
// Create instance of PersonalStorageQueryBuilder
PersonalStorageQueryBuilder queryBuilder = new PersonalStorageQueryBuilder();
queryBuilder.From.Contains("someuser@domain.com");
MessageInfoCollection messages = inbox.GetContents(queryBuilder.GetQuery());
IList<string> deleteList = new List<string>();
foreach (MessageInfo messageInfo in messages)
{
deleteList.Add(messageInfo.EntryIdString);
}
// delete messages having From = "someuser@domain.com"
inbox.DeleteChildItems(deleteList);
}
从 PST 和 OST 文件恢复软删除项目
Aspose.Email for .NET 提供了从 PST 和 OST 文件恢复软删除项目的方法。此功能通过以下实现: PersonalStorage 类,包含 FindAndExtractSoftDeletedItems 方法。此方法允许您定位并恢复已软删除的项目,使您能够恢复可能会丢失的重要数据。恢复的项目将以 … 形式保存在各自的文件夹中。 .msg 文件,确保保持原始文件夹结构。下面的代码示例演示如何在项目中实现此功能:
using (var pst = PersonalStorage.FromFile(fileName))
{
// Soft deleted items are found and extracted
var entries = pst.FindAndExtractSoftDeletedItems();
// The recovered items are iterated through
for (var index = 0; index < entries.Count; index++)
{
// Folder information is obtained by ID
var folderInfo = pst.GetFolderById(entries[index].FolderId);
// A directory for the folder is created if it doesn't exist
if (!Directory.Exists(folderInfo.DisplayName))
{
Directory.CreateDirectory(Path.Combine(path, folderInfo.DisplayName));
}
// The restored item is obtained
var msg = entries[index].Item;
// The restored item is saved as a .msg file
msg.Save(Path.Combine(path, folderInfo.DisplayName, $"{index}.msg"));
}
}
枚举 PST 文件中的软删除邮件
PST 文件中的软删除邮件是指被删除两次的项目——先移动到已删除邮件,然后再次删除。此类邮件并未永久删除,仍可通过编程方式访问。Aspose.Email for .NET 支持检索这些软删除邮件以进行审查或恢复。
要枚举并恢复在 PST 文件中被软删除(删除两次)的项目,请使用 FindAndEnumerateSoftDeletedItems() 方法。此方法检索此类项目的可枚举列表,每个项目都包含邮件及其被删除的文件夹 ID。
下面的代码示例演示如何枚举并恢复已被删除两次的电子邮件。它返回 RestoredItemEntry 表示从 PST 文件中恢复的软删除项条目的类。该类包含以下属性:
-
Item (MapiMessage):恢复的邮件对象。
-
FolderId (string):消息最初被删除的文件夹标识符。
// Load the PST file
using (var pst = PersonalStorage.FromFile("archive.pst"))
{
// Enumerate soft-deleted items
foreach (var entry in pst.FindAndEnumerateSoftDeletedItems())
{
var message = entry.Item;
var folderId = entry.FolderId;
Console.WriteLine($"Subject: {message.Subject}");
Console.WriteLine($"Deleted from Folder ID: {folderId}");
Console.WriteLine("-----------------------------------");
}
}
拆分 PST 文件
拆分为多个 PST
Aspose.Email API 提供将单个 PST 文件拆分为多个指定大小的 PST 文件的功能。
下面的代码示例描述了文件拆分的过程:
-
它首先使用 FromFile 方法的 PersonalStorage 类以指定文件名。
-
然后,它调用 StorageProcessedEventHandler 委托用于处理 StorageProcessed 事件。
-
StorageProcessingEventArgs 为 PersonalStorage.StorageProcessing 事件提供数据。它的 StorageProcessingEventArgs.FileName 属性允许您检索 PST 文件的名称。用于 MergeWith 方法中,它将是当前 PST 与主 PST 合并的名称,以及用于 SplitInto 方法中,它将是当前部分的名称。
-
最后, SplitInto(long chunkSize, string partFileNamePrefix, string path) 重载方法将启动将 PST 存储拆分为更小部分的过程。它接受以下参数:
- chunkSize:每个块的大致字节大小。
- partFileNamePrefix:添加到 PST 每个部分文件名的前缀。如果提供,将在每个文件名前添加该前缀。如果未提供(null 或空),则 PST 部分将不使用前缀创建。
- path:将创建块的文件夹路径。
每个部分的文件名遵循模板:{prefix}part{number}.pst,其中 {prefix} 表示文件名前缀(如果提供),{number} 表示块文件的编号。
var pst = PersonalStorage.FromFile("sample.pst");
// ...
pst.StorageProcessing += (sender, args) =>
{
Console.WriteLine("Storage processing event raised for file: " + args.FileName);
};
// ...
pst.SplitInto(5000000, "prefix_", outputFolderPath);
根据指定标准拆分 PST
以下代码片段展示了如何根据指定标准拆分 PST。
string dataDir = RunExamples.GetDataDir_Outlook();
IList<MailQuery> criteria = new List<MailQuery>();
PersonalStorageQueryBuilder pstQueryBuilder = new PersonalStorageQueryBuilder();
pstQueryBuilder.SentDate.Since(new DateTime(2005, 04, 01));
pstQueryBuilder.SentDate.Before(new DateTime(2005, 04, 07));
criteria.Add(pstQueryBuilder.GetQuery());
pstQueryBuilder = new PersonalStorageQueryBuilder();
pstQueryBuilder.SentDate.Since(new DateTime(2005, 04, 07));
pstQueryBuilder.SentDate.Before(new DateTime(2005, 04, 13));
criteria.Add(pstQueryBuilder.GetQuery());
if (Directory.GetFiles(dataDir + "pathToPst", "*.pst").Length == 0)
{
}
else
{
string[] files = Directory.GetFiles(dataDir + "pathToPst");
foreach (string file in files)
{
if(file.Contains(".pst"))
File.Delete(file);
}
}
using (PersonalStorage personalStorage = PersonalStorage.FromFile(dataDir + "PersonalStorage_New.pst"))
{
personalStorage.SplitInto(criteria, dataDir + "pathToPst");
}
合并 PST 文件
合并为单个 PST
它还可以将多个 PST 文件合并为一个 PST 文件。通过为这些操作添加事件,可以跟踪 PST 的拆分和合并过程。
下面的代码片段展示了如何合并为单个 PST。
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Outlook();
string dst = dataDir + "Sub.pst";
totalAdded = 0;
try
{
using (PersonalStorage personalStorage = PersonalStorage.FromFile(dst))
{
// The events subscription is an optional step for the tracking process only.
personalStorage.StorageProcessed += PstMerge_OnStorageProcessed;
personalStorage.ItemMoved += PstMerge_OnItemMoved;
// Merges with the pst files that are located in separate folder.
personalStorage.MergeWith(Directory.GetFiles(dataDir + @"MergePST\"));
Console.WriteLine("Total messages added: {0}", totalAdded);
}
Console.WriteLine(Environment.NewLine + "PST merged successfully at " + dst);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose Email License. You can purchase full license or get 30 day temporary license from http:// Www.aspose.com/purchase/default.aspx.");
}
Try it out!
使用免费工具在线合并多个电子邮件文件为一个单一文件 Aspose.Email 合并应用.
从另一个 PST 合并文件夹
下面的代码片段展示了如何从另一个 PST 合并文件夹。
string dataDir = RunExamples.GetDataDir_Outlook();
try
{
using (PersonalStorage destinationPst = PersonalStorage.FromFile(dataDir + @"destination.pst"))
using (PersonalStorage sourcePst = PersonalStorage.FromFile(dataDir + @"source.pst"))
{
FolderInfo destinationFolder = destinationPst.RootFolder.AddSubFolder("FolderFromAnotherPst");
FolderInfo sourceFolder = sourcePst.GetPredefinedFolder(StandardIpmFolder.DeletedItems);
// The events subscription is an optional step for the tracking process only.
destinationFolder.ItemMoved += destinationFolder_ItemMoved;
// Merges with the folder from another pst.
destinationFolder.MergeWith(sourceFolder);
Console.WriteLine("Total messages added: {0}", totalAdded);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose Email License. You can purchase full license or get 30 day temporary license from http:// Www.aspose.com/purchase/default.aspx.");
}