Zarządzanie wiadomościami w plikach PST
Uzyskaj informacje o wiadomościach z pliku Outlook PST
W Odczyt plików PST i pobieranie informacji W artykule omówiliśmy, jak załadować plik Outlook PST i przeglądać jego foldery, aby uzyskać nazwy folderów oraz liczbę wiadomości w nich. Ten artykuł wyjaśnia, jak odczytać wszystkie foldery i podfoldery w pliku PST oraz wyświetlić informacje o wiadomościach, np. temat, nadawcę i odbiorcę. Plik Outlook PST może zawierać zagnieżdżone foldery. Aby uzyskać informacje o wiadomościach z tych folderów, jak również z folderów najwyższego poziomu, użyj rekurencyjnej metody do odczytu wszystkich folderów. Poniższy fragment kodu pokazuje, jak odczytać plik Outlook PST i wyświetlić zawartość folderów oraz wiadomości rekurencyjnie.
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);
}
}
}
Wyodrębnianie wiadomości z plików PST
Ten artykuł pokazuje, jak odczytać pliki PST programu Microsoft Outlook i wyodrębnić wiadomości. Wiadomości są następnie zapisywane na dysku w formacie MSG.
Wypróbuj!
Uruchom ConversationThread prosty projekt aplikacji, w którym można zbadać ciekawe zastosowanie funkcji Aspose.Email do odczytywania e‑maili z PST i znajdowania wątków konwersacji.
Poniższy fragment kodu pokazuje, jak wyodrębnić wiadomości z pliku PST:
- Użyj metody rekurencyjnej do przeglądania wszystkich folderów (włącznie z zagnieżdżonymi) i wywołaj metodę PersonalStorage.ExtractMessage(), aby pobrać wiadomości Outlook do instancji MapiMessage klasa.
- Następnie wywołaj metodę MapiMessage.Save(), aby zapisać wiadomość na dysku lub do strumienia w formacie 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);
}
}
}
Identyfikacja typów elementów MAPI
Ten MapiItemType enum reprezentuje typ elementu MAPI, który może być explicite konwertowany na obiekt odpowiadającej klasy pochodnej od IMapiMessageItem interfejs. Dzięki temu użytkownicy mogą uniknąć sprawdzania MessageClass wartość własności przed konwersją wiadomości.
Poniższy przykład kodu pokazuje, jak zdefiniować typ elementu do konwersji:
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;
}
}
Wyszukiwanie i pobieranie wiadomości
Aspose.Email udostępnia następujące przeciążone metody FolderInfo klasa do filtrowania i pobierania wiadomości:
- IEnumerable
EnumerateMessages(MailQuery mailQuery) - Filtruj wiadomości przy użyciu MailQuery. - IEnumerable
EnumerateMessages(MessageKind kind) - Pobierz wiadomości według typu (MessageKind). - IEnumerable
EnumerateMessages(int startIndex, int count) - Paginuj pobieranie wiadomości, używając indeksu początkowego i liczby.
Paginowane pobieranie zawartości folderu
Podczas pracy z dużymi folderami PST pobieranie wszystkich wiadomości naraz może być nieefektywne. Aby poprawić wydajność i kontrolę, Aspose.Email dla .NET oferuje wsparcie paginacji w FolderInfo.GetContents metoda. Ta metoda pobiera podzbiór wiadomości, które spełniają określone zapytanie, zaczynając od podanego indeksu i ograniczając liczbą. Pozwala to pobierać wiadomości w mniejszych, łatwych do obsługi partiach. Metoda przyjmuje następujące parametry:
IList<MessageInfo> FolderInfo.GetContents(MailQuery query, int startIndex, int count)
-
query — filtr do zastosowania na wiadomościach (opcjonalny)
-
startIndex — indeks zerowy, od którego rozpocząć pobieranie
-
count — liczba wiadomości do zwrócenia
Poniższy przykład kodu demonstruje, jak zaimplementować tę metodę w projekcie:
// 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}");
}
}
}
Zapisz wiadomości bezpośrednio z PST do strumienia
Aby zapisać wiadomości z pliku PST bezpośrednio do strumienia, bez wyodrębniania MsgInfo dla wiadomości, użyj metody SaveMessageToStream(). Poniższy fragment kodu pokazuje, jak zapisać wiadomości bezpośrednio z PST do strumienia.
// 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);
}
}
}
Wyodrębnij określoną liczbę wiadomości
Poniższy fragment kodu pokazuje, jak wyodrębnić określoną liczbę wiadomości z PST. Po prostu podaj indeks pierwszej wiadomości oraz łączną liczbę wiadomości do wyodrębnienia.
FolderInfo inbox = personalStorage.RootFolder.GetSubFolder("Inbox");
// Extracts messages starting from 10th index top and extract total 100 messages
MessageInfoCollection messages = inbox.GetContents(10, 100);
Pobierz całkowitą liczbę elementów z PST
Aspose.Email udostępnia GetTotalItemsCount() metoda PersonalStorage.Store właściwość. Zwraca całkowitą liczbę elementów wiadomości zawartych w PST.
Poniższy przykład kodu pokazuje, jak pobrać całkowitą liczbę elementów (wiadomości, spotkań, kontaktów itp.) przechowywanych w pliku PST:
using (var pst = PersonalStorage.FromFile("my.pst", false))
{
var count = pst.Store.GetTotalItemsCount();
}
Wyodrębnianie załączników bez wyodrębniania całej wiadomości
API Aspose.Email może być użyte do wyodrębniania załączników z wiadomości PST bez wcześniejszego wyodrębniania całej wiadomości. ExtractAttachments metoda PersonalStorage można użyć do tego. Poniższy fragment kodu pokazuje, jak wyodrębnić załączniki bez wyodrębniania pełnej wiadomości.
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);
}
}
}
}
}
}
Wyodrębnianie odbiorców wiadomości z plików PST
Odbiorcy wiadomości mogą być wyodrębnieni z plików PST przy użyciu identyfikatora wpisu wiadomości. Ta funkcja jest dostępna w PersonalStorage klasy. Poniższe przykłady kodu pokazują, jak wyodrębnić odbiorców wiadomości:
przez EntryId (przy użyciu ExtractRecipients(string entryId) metoda PersonalStorage klasy)
using (var pst = PersonalStorage.FromFile(fileName))
{
// Recipients are extracted using the entry ID
var recipients = pst.ExtractRecipients("AAAAADzSMygQQFJOkKwVhb8v5EUkASAA");
}
z MessageInfo (używając MapiRecipientCollection ExtractRecipients(MessageInfo messageInfo) metodą)
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);
}
}
Wyszukiwanie wiadomości i folderów
Wyszukiwanie według kryteriów
Pliki Personal Storage (PST) mogą zawierać ogromną ilość danych. Wyszukiwanie danych, które spełniają określone kryteria w tak dużych plikach, wymaga w kodzie wielu punktów kontrolnych, aby odfiltrować informacje. Z PersonalStorageQueryBuilder klasa, Aspose.Email umożliwia wyszukiwanie określonych rekordów w PST na podstawie podanych kryteriów wyszukiwania. W PST można wyszukiwać wiadomości według parametrów takich jak nadawca, odbiorca, temat, ważność wiadomości, obecność załączników, rozmiar wiadomości, a nawet ID wiadomości. PersonalStorageQueryBuilder może być również użyta do wyszukiwania podfolderów.
Wyszukiwanie wiadomości i folderów w PST
Poniższy fragment kodu pokazuje, jak używać PersonalStorageQueryBuilder klasa do wyszukiwania zawartości w PST na podstawie różnych kryteriów wyszukiwania. Na przykład pokazuje wyszukiwanie w PST według:
- Ważność wiadomości.
- Klasa wiadomości.
- Obecność załączników.
- Rozmiar wiadomości.
- Nieprzeczytane wiadomości.
- Nieprzeczytane wiadomości z załącznikami oraz
- foldery o określonej nazwie podfolderu.
// 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);
}
Wyszukiwanie z ignorowaniem wielkości liter
Poniższy fragment kodu pokazuje, jak wyszukać ciąg w PST z parametrem ignorowania wielkości liter.
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);
}
Wyszukiwanie tematów wiadomości po wielu słowach kluczowych
Możesz użyć MailQueryBuilder.Or metoda do znajdowania wiadomości, których temat zawiera przynajmniej jedno z podanych słów, jak pokazano poniżej:
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);
}
}
Manipulowanie wiadomościami
Przenoszenie elementów do innych folderów
Aspose.Email umożliwia przenoszenie elementów ze źródłowego folderu do innego folderu w tym samym pliku Personal Storage (PST). Obejmuje to:
- Przenoszenie określonego folderu do nowego folderu nadrzędnego.
- Przenoszenie określonych wiadomości do nowego folderu.
- Przenoszenie zawartości do nowego folderu.
- Przenoszenie podfolderów do nowego folderu nadrzędnego.
Poniższy fragment kodu pokazuje, jak przenieść elementy, takie jak wiadomości i foldery, ze źródłowego folderu do innego folderu w tym samym pliku 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);
}
Zaktualizuj właściwości wiadomości
Czasami konieczne jest zaktualizowanie niektórych właściwości wiadomości, takich jak zmiana tematu, oznaczenie ważności wiadomości i podobne. Aktualizacja wiadomości w pliku PST, z takimi zmianami w właściwościach wiadomości, może być osiągnięta przy użyciu FolderInfo.ChangeMessages metoda. Ten artykuł pokazuje, jak zaktualizować wiadomości hurtowo w pliku PST w celu zmiany właściwości. Poniższy fragment kodu pokazuje, jak zaktualizować właściwości wiadomości w trybie hurtowym dla wielu wiadomości w pliku 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);
Aktualizacja własnych właściwości
Czasami wymagane jest oznaczenie elementów, które zostały przetworzone w pliku PST. API Aspose.Email umożliwia to za pomocą MapiProperty i MapiNamedProperty. Poniższe metody są pomocne w realizacji tego.
- ctor MapiNamedProperty(long propertyTag, string nameIdentifier, Guid propertyGuid, byte[] propertyValue)
- ctor MapiNamedProperty(long propertyTag, long nameIdentifier, Guid propertyGuid, byte[] propertyValue)
- FolderInfo.ChangeMessages(MapiPropertyCollection updatedProperties) - zmienia wszystkie wiadomości w folderze
- PersonalStorage.ChangeMessage(string entryId, MapiPropertyCollection updatedProperties) - zmienia właściwości wiadomości
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;
}
Usuwanie wiadomości
Ten artykuł pokazuje, jak używać FolderInfo klasa do uzyskiwania dostępu do konkretnych folderów w pliku PST. Aby usunąć wiadomości z podfolderu Sent wcześniej załadowanego lub utworzonego pliku PST:
- Utwórz instancję FolderInfo klasę i załaduj go zawartością podfolderu sent.
- Usuń wiadomości z folderu Sent, wywołując FolderInfo.DeleteChildItem() metoda i przekazanie MessageInfo.EntryId jako parametr. Poniższy fragment kodu pokazuje, jak usunąć wiadomości z podfolderu Sent w pliku 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");
}
}
Usuń foldery
Możesz usunąć folder PST, przenosząc go do folderu Usunięte elementy.
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);
}
Zaletą tej metody jest to, że usunięty folder można łatwo odzyskać.
FolderInfo someFolder = deletedItemsFolder.GetSubFolder("Some folder");
pst.MoveItem(someFolder, pst.RootFolder);
Możesz również trwale usunąć folder z folderu Usunięte elementy, jeśli to konieczne.
deletedItemsFolder.DeleteChildItem(emptyFolder.EntryId);
Ten DeleteChildItem() metodę można używać do dowolnych folderów, jeśli chcesz natychmiast i trwale usunąć podfolder, pomijając folder Usunięte elementy.
FolderInfo someFolder = pst.RootFolder.GetSubFolder("Some folder");
pst.RootFolder.DeleteChildItem(someFolder.EntryId);
Usuwanie elementów z PST
Usuwaj elementy (foldery lub wiadomości) z tabeli osobistego magazynu (PST) przy użyciu unikalnego entryId powiązanego z elementem, wywołując metodę DeleteItem(string entryId) klasy PersonalStorage klasa.
Poniższy fragment kodu można użyć do wywołania metody DeleteItem i przekazania entryId jako parametru:
var pst = PersonalStorage.FromFile("sample.pst");
// ...
pst.DeleteItem(entryId);
// ...
Uwaga:
- Ta metoda trwale usuwa element z pliku PST i nie może być cofnięta. Zachowaj ostrożność przy jej używaniu, aby uniknąć przypadkowej utraty danych.
- Zgodnie z przyjętymi konwencjami, upewnij się, że entryId jest prawidłowy i odpowiada istniejącemu elementowi w pliku PST.
- W przeciwnym razie zostanie zgłoszony wyjątek. Zaleca się posiadanie kopii zapasowej pliku PST lub wprowadzenie odpowiednich środków umożliwiających odzyskanie usuniętych elementów w razie potrzeby.
Masowe usuwanie
API Aspose.Email może być użyte do zbiorczego usuwania elementów z pliku PST. Osiąga się to za pomocą DeleteChildItems() metoda, która przyjmuje listę elementów Entry ID odnoszących się do elementów do usunięcia. Poniższy fragment kodu pokazuje, jak usunąć elementy zbiorczo z pliku 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);
}
Odzyskaj miękko usunięte elementy z plików PST i OST
Aspose.Email dla .NET udostępnia metodę odzyskiwania miękko usuniętych elementów z plików PST i OST. Funkcjonalność ta jest realizowana poprzez PersonalStorage klasa, która zawiera FindAndExtractSoftDeletedItems metoda. Ta metoda umożliwia zlokalizowanie i przywrócenie elementów, które zostały miękko usunięte, co pozwala odzyskać ważne dane, które w przeciwnym razie mogłyby zostać utracone. Odzyskane elementy są zapisywane w odpowiednich folderach jako .msg pliki, zapewniając zachowanie oryginalnej struktury folderów. Poniższy przykład kodu demonstruje, jak wdrożyć tę funkcję w swoim projekcie:
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"));
}
}
Wyliczanie miękko usuniętych wiadomości w plikach PST
Miękko usunięte wiadomości w pliku PST to elementy, które zostały usunięte dwukrotnie — najpierw przeniesione do folderu Usunięte przedmioty, a następnie ponownie usunięte. Takie wiadomości nie są trwale wymazane i nadal można uzyskać do nich dostęp programowo. Aspose.Email dla .NET obsługuje pobieranie tych miękko usuniętych wiadomości w celu przeglądu lub odzyskania.
Aby wyliczyć i odzyskać elementy, które zostały miękko usunięte (usunięte dwukrotnie) w plikach PST, użyj FindAndEnumerateSoftDeletedItems() metodę. Metoda ta zwraca listę wyliczalną takich elementów, z których każdy zawiera zarówno wiadomość, jak i identyfikator folderu, z którego została usunięta.
Poniższy przykład kodu demonstruje, jak wyliczyć i odzyskać e‑maile, które zostały usunięte dwukrotnie. Zwraca RestoredItemEntry klasa reprezentująca wpis dla miękko usuniętego elementu odzyskanego z pliku PST. Klasa zawiera następujące właściwości:
-
Item (MapiMessage): Odzyskany obiekt wiadomości.
-
FolderId (string): Identyfikator folderu, z którego wiadomość została pierwotnie usunięta.
// 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("-----------------------------------");
}
}
Podziel pliki PST
Podziel na wiele plików PST
API Aspose.Email umożliwia podzielenie jednego pliku PST na wiele plików PST o określonym rozmiarze.
Poniższy przykład kodu opisuje proces podziału pliku:
-
Najpierw używa FromFile metoda PersonalStorage klasę w celu określenia nazwy pliku.
-
Następnie wywołuje StorageProcessedEventHandler delegat do obsługi zdarzenia StorageProcessed.
-
StorageProcessingEventArgs dostarcza danych dla zdarzenia PersonalStorage.StorageProcessing. Jego StorageProcessingEventArgs.FileName właściwość umożliwia pobranie nazwy pliku PST. Dla MergeWith metoda zwróci nazwę bieżącego pliku PST, który ma być scalony z głównym, oraz dla SplitInto metoda zwróci nazwę bieżącej części.
-
Na koniec, SplitInto(long chunkSize, string partFileNamePrefix, string path) przeciążona metoda uruchomi podział magazynu PST na mniejsze części. Przyjmuje następujące parametry:
- chunkSize: Przybliżony rozmiar każdej części w bajtach.
- partFileNamePrefix: Prefiks, który ma zostać dodany do nazwy pliku każdej części PST. Jeśli zostanie podany, prefiks zostanie dodany na początek każdej nazwy pliku. Jeśli nie zostanie podany (null lub pusty), części PST zostaną utworzone bez prefiksu.
- path: Ścieżka folderu, w którym zostaną utworzone części.
Nazwa pliku każdej części ma szablon: {prefix}part{number}.pst, gdzie {prefix} oznacza prefiks nazwy pliku (jeśli podany), a {number} oznacza numer części.
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);
Podział PST na podstawie określonego kryterium
Poniższy fragment kodu pokazuje, jak podzielić plik PST wg określonego kryterium.
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");
}
Scal pliki PST
Scal do jednego pliku PST
Może również scalać wiele plików PST w jeden plik PST. Zarówno operacje dzielenia, jak i scalania PST można śledzić, dodając zdarzenia do tych operacji.
Poniższy fragment kodu pokazuje, jak scalić do jednego pliku 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.");
}
Wypróbuj!
Scal i połącz wiele plików e‑mail online w jeden, korzystając z darmowego Aspose.Email Merger App.
Scal foldery z innego pliku PST
Poniższy fragment kodu pokazuje, jak scalić foldery z innego pliku 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.");
}