Praca z wiadomościami w pliku PST
Dodawanie wiadomości do plików PST
Utwórz nowy plik PST i dodaj podfoldery pokazało, jak utworzyć plik PST i dodać do niego podfolder. Dzięki Aspose.Email możesz dodawać wiadomości do podfolderów pliku PST, który został utworzony lub wczytany. Ten artykuł dodaje dwie wiadomości z dysku do podfolderu Inbox w pliku PST. Użyj PersonalStorage i FolderInfo klasy do dodawania wiadomości do plików PST. Aby dodać wiadomości do folderu Inbox w pliku PST:
- Utwórz instancję klasy FolderInfo i załaduj ją zawartością folderu Inbox.
- Dodaj wiadomości z dysku do folderu Inbox, wywołując FolderInfo.addMessage() metoda. FolderInfo klasa udostępnia addMessages metoda umożliwiająca dodanie dużej liczby wiadomości do folderu, zmniejszając operacje I/O na dysku i poprawiając wydajność. Pełny przykład można znaleźć poniżej, w Dodawanie wiadomości w trybie zbiorczym.
Poniższe fragmenty kodu pokazują, jak dodać wiadomości do podfolderu PST o nazwie Inbox.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Create new PST
PersonalStorage personalStorage = PersonalStorage.create(dataDir, FileFormatVersion.Unicode);
// Add new folder "Inbox"
personalStorage.getRootFolder().addSubFolder("Inbox");
// Select the "Inbox" folder
FolderInfo inboxFolder = personalStorage.getRootFolder().getSubFolder("Inbox");
// Add some messages to "Inbox" folder
inboxFolder.addMessage(MapiMessage.fromFile(dataDir + "MapiMsgWithPoll.msg"));
Dodawanie wiadomości w trybie zbiorczym
Dodawanie pojedynczych wiadomości do pliku PST wymaga większej liczby operacji I/O na dysku, co może spowolnić wydajność. W celu poprawy wydajności wiadomości mogą być dodawane do PST w trybie zbiorczym, aby zminimalizować operacje I/O. The addMessages(Iterable
Wczytywanie wiadomości z dysku
Poniższy fragment kodu pokazuje, jak wczytać wiadomości z dysku.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
private static void addMessagesInBulkMode(String fileName, String msgFolderName) {
try (PersonalStorage personalStorage = PersonalStorage.fromFile(fileName)) {
FolderInfo folder = personalStorage.getRootFolder().getSubFolder("myInbox");
folder.MessageAdded.add(new MessageAddedEventHandler() {
public void invoke(Object sender, MessageAddedEventArgs e) {
onMessageAdded(sender, e);
}
});
folder.addMessages(new MapiMessageCollection(msgFolderName));
}
}
static void onMessageAdded(Object sender, MessageAddedEventArgs e) {
System.out.println(e.getEntryId());
System.out.println(e.getMessage().getSubject());
}
Implementacja Iterable
Poniższy fragment kodu pokazuje, jak stworzyć implementację Iterable.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
public class MapiMessageCollection implements Iterable<MapiMessage> {
private final File folder;
public MapiMessageCollection(String folder) {
this.folder = new File(folder);
}
public Iterator<MapiMessage> iterator() {
return new MapiMessageIterator(folder.listFiles());
}
}
public class MapiMessageIterator implements Iterator<MapiMessage> {
private Queue<String> queue = new LinkedList<String>();
public MapiMessageIterator(File[] listOfFiles) {
for (File file : listOfFiles) {
queue.offer(file.getAbsolutePath());
}
}
public boolean hasNext() {
return !queue.isEmpty();
}
public MapiMessage next() {
return MapiMessage.fromFile(queue.poll());
}
}
Dodawanie wiadomości z innego PST
Aby dodać wiadomości z innego PST, użyj FolderInfo.enumerateMapiMessages() metoda zwracająca Iterable
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
private static void bulkAddFromAnotherPst(String source) {
// The path to the File directory.
String dataDir = "data/";
try (PersonalStorage pst = PersonalStorage.fromFile(source, false)) {
try (PersonalStorage pstDest = PersonalStorage.fromFile(dataDir + "PersonalStorageFile1.pst")) {
// Get the folder by name
FolderInfo folderInfo = pst.getRootFolder().getSubFolder("Contacts");
MessageInfoCollection ms = folderInfo.getContents();
// Get the folder by name
FolderInfo f = pstDest.getRootFolder().getSubFolder("myInbox");
f.MessageAdded.add(new MessageAddedEventHandler() {
public void invoke(Object sender, MessageAddedEventArgs e) {
onMessageAdded(sender, e);
}
});
f.addMessages(folderInfo.enumerateMapiMessages());
FolderInfo fi = pstDest.getRootFolder().getSubFolder("myInbox");
MessageInfoCollection msgs = fi.getContents();
}
}
}
// Handles the MessageAdded event.
static void onMessageAdded(Object sender, MessageAddedEventArgs e) {
System.out.println(e.getEntryId());
System.out.println(e.getMessage().getSubject());
}
Uzyskaj informacje o wiadomościach z pliku Outlook PST
W Odczyt pliku Outlook PST i uzyskanie informacji o folderach oraz podfolderach, omawialiśmy wczytywanie pliku Outlook PST i przeglądanie jego folderów w celu uzyskania nazw folderów oraz liczby wiadomości w nich. Ten artykuł wyjaśnia, jak odczytać wszystkie foldery i podfoldery w pliku PST i wyświetlić informacje o wiadomościach, na przykład temat, nadawcę i odbiorców. FolderInfo.getContents() metoda służy do wyświetlania krótkie informacje o wiadomości takie jak temat, nadawca, odbiorcy. Pod względem wydajności jest to najodpowiedniejsza opcja uzyskiwania podstawowych informacji o wiadomościach. Aby wyodrębnić pełne dane wiadomości, PersonalStorage.extractMessage() dostarczono metodę. Plik Outlook PST może zawierać zagnieżdżone foldery. Aby uzyskać informacje o wiadomościach z nich oraz z folderów najwyższego poziomu, użyj metody rekurencyjnej do odczytania wszystkich folderów. Poniższy fragment kodu pokazuje, jak odczytać plik Outlook PST i wyświetlić zawartość folderów oraz wiadomości rekurencyjnie.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
public static void run() {
// The path to the File directory.
String dataDir = "data/";
// 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
System.out.println("Display Format: " + personalStorage.getFormat());
// Get the folders and messages information
FolderInfo folderInfo = personalStorage.getRootFolder();
// Call the recursive method to display the folder contents
displayFolderContents(folderInfo, personalStorage);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
// This is a recursive method to display contents of a folder
private static void displayFolderContents(FolderInfo folderInfo, PersonalStorage pst) {
// Display the folder name
System.out.println("Folder: " + folderInfo.getDisplayName());
System.out.println("==================================");
// Display information about messages inside this folder
MessageInfoCollection messageInfoCollection = folderInfo.getContents();
for (MessageInfo messageInfo : messageInfoCollection) {
System.out.println("Subject: " + messageInfo.getSubject());
System.out.println("Sender: " + messageInfo.getSenderRepresentativeName());
System.out.println("Recipients: " + messageInfo.getDisplayTo());
System.out.println("------------------------------");
}
// Call this method recursively for each subfolder
if (folderInfo.hasSubFolders() == true) {
for (FolderInfo subfolderInfo : folderInfo.getSubFolders()) {
displayFolderContents(subfolderInfo, pst);
}
}
}
Wyodrębnianie wiadomości z plików PST
Ten artykuł pokazuje, jak odczytywać pliki Microsoft Outlook PST i wyodrębnić wiadomości. Wiadomości są następnie zapisywane na dysku w formacie MSG. Artykuł pokazuje również, jak wyodrębnić określoną liczbę wiadomości z pliku PST. Użyj metody rekurencyjnej, aby przeglądać wszystkie foldery (w tym zagnieżdżone) i wywołać PersonalStorage.extractMessage() metodę, aby uzyskać wiadomości Outlook w instancji MapiMessage klasa. Następnie wywołaj MapiMessage.save() metoda do zapisywania wiadomości na dysk lub do strumienia w formacie MSG. Poniższy fragment kodu pokazuje, jak wyodrębnić wiadomości z pliku PST.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
public static void run() {
// The path to the File directory.
String dataDir = "data/";
// 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
System.out.println("Display Format: " + pst.getFormat());
// get the folders and messages information
FolderInfo folderInfo = pst.getRootFolder();
// Call the recursive method to extract msg files from each folder
extractMsgFiles(folderInfo, pst);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
// This is a recursive method to display contents of a folder
private static void extractMsgFiles(FolderInfo folderInfo, PersonalStorage pst) {
// display the folder name
System.out.println("Folder: " + folderInfo.getDisplayName());
System.out.println("==================================");
// loop through all the messages in this folder
MessageInfoCollection messageInfoCollection = folderInfo.getContents();
for (MessageInfo messageInfo : messageInfoCollection) {
System.out.println("Saving message {0} ...." + messageInfo.getSubject());
// get the message in MapiMessage instance
MapiMessage message = pst.extractMessage(messageInfo);
// save this message to disk in msg format
message.save(message.getSubject().replace(":", " ") + ".msg");
// save this message to stream in msg format
ByteArrayOutputStream messageStream = new ByteArrayOutputStream();
message.save(messageStream);
}
// Call this method recursively for each subfolder
if (folderInfo.hasSubFolders() == true) {
for (FolderInfo subfolderInfo : folderInfo.getSubFolders()) {
extractMsgFiles(subfolderInfo, pst);
}
}
}
Zapisywanie 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 saveMessageToStream() metoda. Poniższy fragment kodu pokazuje, jak zapisać wiadomości bezpośrednio z PST do strumienia.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the File directory.
String dataDir = "data/";
// Load the Outlook file
String path = dataDir + "PersonalStorage.pst";
// Save message to MemoryStream
try (PersonalStorage personalStorage = PersonalStorage.fromFile(path)) {
FolderInfo inbox = personalStorage.getRootFolder().getSubFolder("Inbox");
for (MessageInfo messageInfo : inbox.enumerateMessages()) {
try (ByteArrayOutputStream memeorystream = new ByteArrayOutputStream()) {
personalStorage.saveMessageToStream(messageInfo.getEntryIdString(), memeorystream);
}
}
}
// Save message to file
try (PersonalStorage pst = PersonalStorage.fromFile(path)) {
FolderInfo inbox = pst.getRootFolder().getSubFolder("Inbox");
for (MessageInfo messageInfo : inbox.enumerateMessages()) {
try (FileOutputStream fs = new FileOutputStream(new File(dataDir + messageInfo.getSubject() + ".msg"))) {
pst.saveMessageToStream(messageInfo.getEntryIdString(), fs);
}
}
}
try (PersonalStorage pst = PersonalStorage.fromFile(path)) {
FolderInfo inbox = pst.getRootFolder().getSubFolder("Inbox");
// To enumerate entryId of messages you may use FolderInfo.EnumerateMessagesEntryId() method:
for (String entryId : inbox.enumerateMessagesEntryId()) {
try (ByteArrayOutputStream ms = new ByteArrayOutputStream()) {
pst.saveMessageToStream(entryId, ms);
}
}
}
Wyodrębnianie n wiadomości z pliku PST
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.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
FolderInfo inbox = personalStorage.getRootFolder().getSubFolder("Inbox");
// Extracts messages starting from 10th index top and extract total 100 messages
MessageInfoCollection messages = inbox.getContents(10, 100);
Pobierz łączną liczbę elementów z pliku 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:
try (PersonalStorage pst = PersonalStorage.fromFile("my.pst", false)) {
int count = pst.getStore().getTotalItemsCount();
}
Usuwanie elementów z plików PST
Dodawanie wiadomości do plików PST pokazało, jak dodawać wiadomości do plików PST. Oczywiście możliwe jest również usuwanie elementów (zawartości) z pliku PST i może być pożądane usuwanie wiadomości zbiorczo. Elementy z pliku PST można usuwać przy użyciu FolderInfo.deleteChildItem() metoda. API zapewnia również FolderInfo.deleteChildItems() metoda do zbiorczego usuwania elementów z pliku PST.
Usuwanie wiadomości z plików PST
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.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the File directory.
String dataDir = "data/" + "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();
for (MessageInfo msgInfo : msgInfoColl) {
System.out.println(msgInfo.getSubject() + ": " + msgInfo.getEntryIdString());
if (msgInfo.getSubject().equals("some delete condition")) {
// Delete this item
folderInfo.deleteChildItem(msgInfo.getEntryId());
System.out.println("Deleted this message");
}
}
Usuwanie folderów z plików PST
Możesz usunąć folder PST, przenosząc go do folderu Usunięte elementy.
try (PersonalStorage pst = PersonalStorage.fromFile("test.pst")) {
FolderInfo deletedItemsFolder = pst.getPredefinedFolder(StandardIpmFolder.DeletedItems);
FolderInfo emptyFolder = pst.getRootFolder().getSubFolder("Empty folder");
FolderInfo someFolder = pst.getRootFolder().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.getRootFolder());
Możesz również trwale usunąć folder z folderu Usunięte elementy, jeśli to konieczne.
deletedItemsFolder.deleteChildItem(emptyFolder.getEntryId());
Ten deleteChildItem() metoda może być użyta dla dowolnych folderów, jeśli chcesz natychmiastowo i trwale usunąć podfolder, pomijając folder Usunięte elementy.
FolderInfo someFolder = pst.getRootFolder().getSubFolder("Some folder");
pst.getRootFolder().deleteChildItem(someFolder.getEntryId());
Zbiorcze usuwanie elementów z pliku PST
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.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the File directory.
String dataDir = "data/" + "Sub.pst";
try (PersonalStorage personalStorage = PersonalStorage.fromFile(dataDir)) {
// Get Inbox SubFolder from Outlook file
FolderInfo inbox = personalStorage.getRootFolder().getSubFolder("Inbox");
// Create instance of PersonalStorageQueryBuilder
PersonalStorageQueryBuilder queryBuilder = new PersonalStorageQueryBuilder();
queryBuilder.getFrom().contains("someuser@domain.com");
MessageInfoCollection messages = inbox.getContents(queryBuilder.getQuery());
List<String> deleteList = new ArrayList<String>();
for (MessageInfo messageInfo : messages) {
deleteList.add(messageInfo.getEntryIdString());
}
// delete messages having From = "someuser@domain.com"
inbox.deleteChildItems(deleteList);
}
Wyliczanie i odzyskiwanie miękko usuniętych wiadomości z PST
Możliwe jest pobranie trwale usuniętych wiadomości za pomocą Aspose.Email for Java. Jego API pozwala wyliczyć miękko usunięte wiadomości w plikach PST. Miękko usunięte elementy to wiadomości, które zostały usunięte dwa razy – najpierw przeniesiono je do folderu Usunięte elementy, a następnie usunięto stamtąd. Wiadomości te są nadal odzyskiwalne, a Aspose.Email zapewnia wygodny sposób ich dostępu. PersonalStorage.findAndEnumerateSoftDeletedItems() metoda zwraca kolekcję RestoredItemEntry obiekty. Każdy wpis zawiera:
- MapiMessage item — odzyskana wiadomość.
- String FolderId - identyfikator folderu, do którego pierwotnie należała wiadomość.
Poniższy przykład kodu demonstruje, jak wyliczyć miękko usunięte (odzyskiwalne) elementy e‑mail w plikach PST:
// Load the PST file
try (PersonalStorage pst = PersonalStorage.fromFile(fileName)) {
// Enumerate soft-deleted items
for (RestoredItemEntry entry : pst.findAndEnumerateSoftDeletedItems()) {
MapiMessage message = entry.getItem();
String folderId = entry.getFolderId();
System.out.println("Subject: " + message.getSubject());
System.out.println("Deleted from Folder ID: " + folderId);
System.out.println("-----------------------------------");
}
}
Wyszukiwanie wiadomości i folderów w PST według kryterium
Pliki Personal Storage (PST) mogą zawierać ogromną ilość danych, a wyszukiwanie danych spełniających określone kryteria w tak dużych plikach wymaga w kodzie wielu punktów kontrolnych filtrujących 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.
- Data wiadomości.
- Nieprzeczytane wiadomości.
- Nieprzeczytane wiadomości z załącznikami oraz
- foldery o określonej nazwie podfolderu.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the File directory.
String dataDir = "data/";
try (PersonalStorage personalStorage = PersonalStorage.fromFile(dataDir + "Outlook.pst")) {
FolderInfo folder = personalStorage.getRootFolder().getSubFolder("Inbox");
PersonalStorageQueryBuilder builder = new PersonalStorageQueryBuilder();
// High importance messages
builder.getImportance().equals((int) MapiImportance.High);
MessageInfoCollection messages = folder.getContents(builder.getQuery());
System.out.println("Messages with High Imp:" + messages.size());
builder = new PersonalStorageQueryBuilder();
builder.getMessageClass().equals("IPM.Note");
messages = folder.getContents(builder.getQuery());
System.out.println("Messages with IPM.Note:" + messages.size());
builder = new PersonalStorageQueryBuilder();
// Messages with attachments AND high importance
builder.getImportance().equals((int) MapiImportance.High);
builder.hasFlags(MapiMessageFlags.MSGFLAG_HASATTACH);
messages = folder.getContents(builder.getQuery());
System.out.println("Messages with atts: " + messages.size());
builder = new PersonalStorageQueryBuilder();
// Messages with size > 15 KB
builder.getMessageSize().greater(15000);
messages = folder.getContents(builder.getQuery());
System.out.println("messags size > 15Kb:" + messages.size());
java.util.Calendar c = java.util.Calendar.getInstance();
builder = new PersonalStorageQueryBuilder();
// Messages by Current Date
// (Note that queries by date are not supported for Calendar Items in the Appointments folder)
builder.getSentDate().on(c.getTime(), DateComparisonType.ByDate);
messages = folder.getContents(builder.getQuery());
System.out.println("Messages by Current Date: " + messages.size());
builder = new PersonalStorageQueryBuilder();
// Messages between Dates
// (Note that queries by date are not supported for Calendar Items in the Appointments folder)
c.set(2020, 0, 1, 0, 0, 0);
builder.getSentDate().since(c.getTime());
c.set(2021, 0, 1, 0, 0, 0);
builder.getSentDate().before(c.getTime());
messages = folder.getContents(builder.getQuery());
System.out.println("Messages between Dates: " + messages.size());
builder = new PersonalStorageQueryBuilder();
// Unread messages
builder.hasNoFlags(MapiMessageFlags.MSGFLAG_READ);
messages = folder.getContents(builder.getQuery());
System.out.println("Unread:" + messages.size());
builder = new PersonalStorageQueryBuilder();
// Unread messages with attachments
builder.hasNoFlags(MapiMessageFlags.MSGFLAG_READ);
builder.hasFlags(MapiMessageFlags.MSGFLAG_HASATTACH);
messages = folder.getContents(builder.getQuery());
System.out.println("Unread msgs with atts: " + messages.size());
// Folder with name of 'SubInbox'
builder = new PersonalStorageQueryBuilder();
builder.getFolderName().equals("SubInbox");
FolderInfoCollection folders = folder.getSubFolders(builder.getQuery());
System.out.println("Folder having subfolder: " + folders.size());
builder = new PersonalStorageQueryBuilder();
// Folders with subfolders
builder.hasSubfolders();
folders = folder.getSubFolders(builder.getQuery());
System.out.println(folders.size());
}
Wyszukiwanie ciągu w PST z parametrem ignorowania wielkości liter
Poniższy fragment kodu pokazuje, jak wyszukać ciąg w PST z parametrem ignorowania wielkości liter.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the File directory.
String dataDir = "data/";
try (PersonalStorage personalStorage = PersonalStorage.create(dataDir + "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.getFrom().contains("automated", true);
MailQuery query = builder.getQuery();
MessageInfoCollection coll = folderinfo.getContents(query);
System.out.println(coll.size());
}
Wyszukiwanie tematów wiadomości po wielu słowach kluczowych w pliku PST
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:
PersonalStorageQueryBuilder builder1 = new PersonalStorageQueryBuilder();
builder1.getSubject().contains("Review"); // 'Review' is key word for the search
PersonalStorageQueryBuilder builder2 = new PersonalStorageQueryBuilder();
builder2.getSubject().contains("Error"); // 'Error' is also key word for the search
PersonalStorageQueryBuilder queryBuilder = new PersonalStorageQueryBuilder();
queryBuilder.or(builder1.getQuery(), builder2.getQuery()); // message subjects must contain 'Review' or 'Error' words
try (PersonalStorage storage = PersonalStorage.fromFile("example.pst"))
{
FolderInfo folderInfo = storage.getRootFolder().getSubFolder("Inbox");
MessageInfoCollection messageInfos = folderInfo.getContents(queryBuilder.getQuery());
for (MessageInfo messageInfo : messageInfos)
{
System.out.println(messageInfo.getSubject());
}
}
Stronicowane pobieranie zawartości folderu PST
Popraw wydajność aplikacji i kontrolę podczas nawigacji po dużych folderach. Pobieraj zawartość folderu w sposób stronicowany, używając przeciążenia Aspose.Email dla getContents metoda. Ta metoda - FolderInfo.getContents(MailQuery query, int startIndex, int count) - pobiera podzbiór wiadomości spełniających określone zapytanie, zaczynając od podanego indeksu i ograniczony liczbą. Poniższy przykład kodu demonstruje pobieranie stronicowane i przetwarzanie przefiltrowanych wiadomości z folderu PST:
// Load the PST file
try (PersonalStorage pst = PersonalStorage.fromFile(fileName)) {
// Access a specific subfolder
FolderInfo folder = pst.getRootFolder().getSubFolder("Inbox");
// Build a query to filter messages by sender address
PersonalStorageQueryBuilder queryBuilder = new PersonalStorageQueryBuilder();
queryBuilder.getFrom().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
MessageInfoCollection messages = folder.getContents(queryBuilder.getQuery(), startIndex, pageSize);
for (MessageInfo messageInfo : messages) {
// Output basic info about each message
System.out.println("Subject: " + messageInfo.getSubject() + ", Sender: " + messageInfo.getSenderRepresentativeName());
}
}
}
Przenoszenie elementów do innych folderów pliku PST
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ślonej 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.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
try (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.get(0), deleted);
// Move all inbox subfolders and subfolder contents to the Deleted Items
inbox.moveSubfolders(deleted);
subfolder.moveContents(deleted);
}
Aktualizowanie właściwości wiadomości w pliku PST
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.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the File directory.
String dataDir = "data/" + "Sub.pst";
// Load the Outlook PST file
PersonalStorage personalStorage = PersonalStorage.fromFile(dataDir);
// Get Requierd Subfolder
FolderInfo inbox = personalStorage.getRootFolder().getSubFolder("Inbox");
// find messages having From = "someuser@domain.com"
PersonalStorageQueryBuilder queryBuilder = new PersonalStorageQueryBuilder();
queryBuilder.getFrom().contains("someuser@domain.com");
// Get Contents from Query
MessageInfoCollection messages = inbox.getContents(queryBuilder.getQuery());
// Save (MessageInfo,EntryIdString) in List
List<String> changeList = new ArrayList<String>();
for (MessageInfo messageInfo : messages) {
changeList.add(messageInfo.getEntryIdString());
}
// Compose the new properties
MapiPropertyCollection updatedProperties = new MapiPropertyCollection();
updatedProperties.add(MapiPropertyTag.PR_SUBJECT_W, new MapiProperty(MapiPropertyTag.PR_SUBJECT_W, "New Subject".getBytes(Charset.forName("utf-16le"))));
updatedProperties.add(MapiPropertyTag.PR_IMPORTANCE, new MapiProperty(MapiPropertyTag.PR_IMPORTANCE, BitConverter.getBytesInt64(2)));
// update messages having From = "someuser@domain.com" with new properties
inbox.changeMessages(changeList, updatedProperties);
Aktualizacja niestandardowych właściwości w pliku PST
Czasami konieczne jest oznaczenie elementów przetwarzanych w pliku PST. API Aspose.Email umożliwia to przy użyciu MapiProperty i MapiNamedProperty. Następujące metody są pomocne w osiągnięciu tego celu.
- constructor MapiNamedProperty(long propertyTag, String nameIdentifier, UUID propertyGuid, byte[] propertyValue)
- constructor MapiNamedProperty(long propertyTag, long nameIdentifier, UUID propertyGuid, byte[] propertyValue)
- FolderInfo.changeMessages(MapiPropertyCollection updatedProperties) - zmienia wszystkie wiadomości w folderze
- PersonalStorage.changeMessage(String entryId, MapiPropertyCollection updatedProperties) - zmiana właściwości wiadomości
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
public static void run() {
// The path to the File directory.
String dataDir = "data/" + "Sub.pst";
try (PersonalStorage personalStorage = PersonalStorage.fromFile(dataDir)) {
FolderInfo testFolder = personalStorage.getRootFolder().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, "test_address@org.com".getBytes(Charset.forName("utf-16le")));
MapiProperty namedProperty1 = new MapiNamedProperty(generateNamedPropertyTag(0L, MapiPropertyType.PT_LONG), "ITEM_ID", UUID.randomUUID(),
BitConverter.getBytesInt64(123));
MapiProperty namedProperty2 = new MapiNamedProperty(generateNamedPropertyTag(1L, MapiPropertyType.PT_LONG), 0x0000870C,
UUID.fromString("0006200A-0000-0000-C000-000000000046"), BitConverter.getBytesInt64(0));
newProperties.add(namedProperty1.getTag(), namedProperty1);
newProperties.add(namedProperty2.getTag(), namedProperty2);
newProperties.add(property.getTag(), property);
testFolder.changeMessages(testFolder.enumerateMessagesEntryId(), newProperties);
}
}
private static long generateNamedPropertyTag(long index, int dataType) {
return (((0x8000 | index) << 16) | (long) dataType) & 0x00000000FFFFFFFFL;
}
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 całej wiadomości.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the File directory.
String dataDir = "data/";
try (PersonalStorage personalstorage = PersonalStorage.fromFile(dataDir + "Outlook.pst")) {
FolderInfo folder = personalstorage.getRootFolder().getSubFolder("Inbox");
for (String messageInfo : folder.enumerateMessagesEntryId()) {
MapiAttachmentCollection attachments = personalstorage.extractAttachments(messageInfo);
if (attachments.size() != 0) {
for (MapiAttachment attachment : attachments) {
if (attachment.getLongFileName() != null && !attachment.getLongFileName().isEmpty()) {
if (attachment.getLongFileName().contains(".msg")) {
continue;
} else {
attachment.save(dataDir + "Attachments/" + attachment.getLongFileName());
}
}
}
}
}
}
Dodawanie plików do PST
Kluczowa funkcjonalność Microsoft Outlook to zarządzanie e‑mailami, kalendarzami, zadaniami, kontaktami i wpisami dziennika. Dodatkowo, pliki mogą być również dodawane do folderu PST, a powstały plik PST przechowuje informacje o dodanych dokumentach. Aspose.Email umożliwia dodawanie plików do folderu w taki sam sposób, jak dodawanie wiadomości, kontaktów, zadań i wpisów dziennika do PST. Poniższy fragment kodu pokazuje, jak dodać dokumenty do folderu PST przy użyciu Aspose.Email.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the File directory.
String dataDir = "data/";
try (PersonalStorage personalStorage = PersonalStorage.create(dataDir + "Ps1_out.pst", FileFormatVersion.Unicode)) {
FolderInfo folder = personalStorage.getRootFolder().addSubFolder("Files");
// Add Document.doc file with the "IPM.Document" message class by default.
folder.addFile(dataDir + "attachment_1.doc", null);
}