Робота з повідомленнями у PST файлі

Contents
[ ]

Додавання повідомлень до файлів PST

Створити новий файл PST та додати підпапки показано, як створити файл PST і додати до нього підпапку. За допомогою Aspose.Email ви можете додавати повідомлення до підпапок файлу PST, який ви створили або завантажили. У цій статті додаються два повідомлення з диска до підпапки Inbox у PST. Використовуйте PersonalStorage і FolderInfo класи для додавання повідомлень до файлів PST. Щоб додати повідомлення до папки Inbox у файлі PST:

  1. Створіть екземпляр класу FolderInfo та завантажте його вмістом папки Inbox.
  2. Додайте повідомлення з диска до папки Inbox, викликавши FolderInfo.addMessage() метод. FolderInfo клас надає addMessages метод, який дозволяє додати велику кількість повідомлень до папки, зменшуючи операції вводу/виводу на диск і підвищуючи продуктивність. Повний приклад можна знайти нижче, у Додавання пакетних повідомлень.

Нижче наведені фрагменти коду, які показують, як додати повідомлення до підпапки PST під назвою 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"));

Додавання пакетних повідомлень

Додавання окремих повідомлень до PST передбачає більше операцій вводу/виводу на диск і тому може сповільнити продуктивність. Для підвищення продуктивності повідомлення можна додавати до PST у пакетному режимі, щоб мінімізувати операції вводу/виводу. The addMessages(Iterable messages) метод дозволяє визначити діапазон повідомлень, які будуть додані до PST для підвищення продуктивності, і може бути використаний у наступних сценаріях. Крім того, подія MessageAdded виникає, коли повідомлення додається до папки.

Завантаження повідомлень з диска

Наступний фрагмент коду показує, як завантажити повідомлення з диска.

// 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());
}

Ітерабельна реалізація

Наступний фрагмент коду показує, як створити реалізацію 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());
    }
}

Додавання повідомлень з іншого PST

Для додавання повідомлень з іншого PST використайте FolderInfo.enumerateMapiMessages() метод, який повертає Iterable. Наступний фрагмент коду показує, як додати повідомлення з іншого PST.

// 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());
}

Отримання інформації про повідомлення з Outlook PST‑файла

У Читання файлу Outlook PST та отримання інформації про папки та підпапки, ми розглядали завантаження Outlook PST‑файлу та перегляд його папок для отримання імен папок та кількості повідомлень у них. У цій статті пояснюється, як прочитати всі папки та підпапки у PST‑файлі та відобразити інформацію про повідомлення, наприклад, тему, відправника та отримувачів. FolderInfo.getContents() метод використовується для відображення коротка інформація про повідомлення як тема, відправник, отримувачі. З точки зору продуктивності це найкращий варіант для отримання первинної інформації про повідомлення. Щоб витягнути повні дані повідомлення, PersonalStorage.extractMessage() надається метод. Outlook PST‑файл може містити вкладені папки. Щоб отримати інформацію про повідомлення з них, а також з папок верхнього рівня, використайте рекурсивний метод для читання всіх папок. Наступний фрагмент коду показує, як прочитати Outlook 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 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);
        }
    }
}

Витягування повідомлень з PST‑файлів

У цій статті показано, як читати файли Microsoft Outlook PST та витягнути повідомлення. Потім повідомлення зберігаються на диск у форматі MSG. У статті також показано, як витягнути певну кількість повідомлень з PST‑файлу. Використайте рекурсивний метод для перегляду всіх папок (включаючи вкладені) та викличте PersonalStorage.extractMessage() метод, щоб отримати Outlook‑повідомлення у екземпляр MapiMessage клас. Після цього викличте MapiMessage.save() метод для збереження повідомлення на диск або у потік у форматі MSG. Наступний фрагмент коду показує, як витягнути повідомлення з 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);
        }
    }
}

Збереження повідомлень безпосередньо з PST у потік

Щоб зберегти повідомлення з PST‑файлу безпосередньо у потік, не витягуючи MsgInfo для повідомлень, використайте saveMessageToStream() метод. Наступний фрагмент коду показує, як зберегти повідомлення безпосередньо з 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/";

// 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);
        }
    }
}

Видобуток n повідомлень з PST‑файлу

Наступний фрагмент коду показує, як витягнути певну кількість повідомлень з PST. Просто вкажіть індекс першого повідомлення та загальну кількість повідомлень для витягнення.

// 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);

Отримання загальної кількості елементів з PST‑файлу

Aspose.Email надає GetTotalItemsCount() метод PersonalStorage.Store властивість. Вона повертає загальну кількість повідомлень, що містяться у PST.

Наступний зразок коду показує, як отримати загальну кількість елементів (повідомлень, зустрічей, контактів тощо), що зберігаються у PST‑файлі:

try (PersonalStorage pst = PersonalStorage.fromFile("my.pst", false)) {
    int count = pst.getStore().getTotalItemsCount();
}

Видалення елементів з PST‑файлів

Add Messages to PST Files показано, як додавати повідомлення у PST‑файли. Звісно, також можливо видаляти елементи (вміст) з PST‑файлу, і може бути потрібним масове видалення повідомлень. Елементи з PST‑файлу можна видаляти за допомогою FolderInfo.deleteChildItem() метод. API також надає FolderInfo.deleteChildItems() метод для масового видалення елементів з PST‑файлу.

Видалення повідомлень з PST‑файлів

Ця стаття показує, як використовувати FolderInfo клас для доступу до конкретних папок у PST‑файлі. Щоб видалити повідомлення з підпапки Sent раніше завантаженого або створеного PST‑файлу:

  1. Створіть екземпляр FolderInfo клас і завантаживши його вмістом підпапки Sent.
  2. Видаліть повідомлення з папки Sent, викликавши FolderInfo.deleteChildItem() метод і передаючи MessageInfo.EntryId як параметр. Наступний фрагмент коду показує, як видалити повідомлення з підпапки Sent у 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");
    }
}

Видалення папок з PST‑файлів

Ви можете видалити папку PST, перемістивши її до папки Видалені елементи.

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);
}

Перевага цього методу полягає в тому, що видалена папка може бути легко відновлена.

FolderInfo someFolder = deletedItemsFolder.getSubFolder("Some folder");
pst.moveItem(someFolder, pst.getRootFolder());

За потреби ви також можете назавжди видалити папку з папки Видалені елементи.

deletedItemsFolder.deleteChildItem(emptyFolder.getEntryId());

The deleteChildItem() метод можна використати для будь‑яких папок, якщо ви бажаєте негайно та назавжди видалити підпапку, обходячи папку Видалені елементи.

FolderInfo someFolder = pst.getRootFolder().getSubFolder("Some folder");
pst.getRootFolder().deleteChildItem(someFolder.getEntryId());

Масове видалення елементів з PST‑файлу

API Aspose.Email можна використати для масового видалення елементів з PST‑файла. Це здійснюється за допомогою deleteChildItems() метод, який приймає список елементів Entry ID, що вказують на елементи для видалення. Наступний фрагмент коду показує, як масово видаляти елементи з 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);
}

Перелічення та відновлення м’яко видалених повідомлень з PST

Можливо отримати назавжди видалені повідомлення за допомогою Aspose.Email для Java. Його API дозволяє перелічити м’яко видалені повідомлення у PST‑файлах. М’яко видалені елементи — це повідомлення, які були видалені двічі: спочатку переміщені до папки Видалені елементи, а потім звідти видалені. Ці повідомлення все ще можна відновити, і Aspose.Email надає зручний спосіб доступу до них. PersonalStorage.findAndEnumerateSoftDeletedItems() метод повертає колекцію RestoredItemEntry об’єкти. Кожен запис містить:

  • MapiMessage item — відновлене повідомлення.
  • String FolderId - ідентифікатор папки, в якій первісно знаходилося повідомлення.

Наступний зразок коду демонструє, як перелічити м’яко видалені (відновлювані) електронні елементи у 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("-----------------------------------");
    }
}

Пошук повідомлень і папок у PST за критерієм

Файли Personal Storage (PST) можуть містити величезну кількість даних, і пошук даних, що відповідають певному критерію у таких великих файлах, вимагає включення кількох контрольних точок у коді для фільтрації інформації. За допомогою PersonalStorageQueryBuilder клас, Aspose.Email дозволяє шукати конкретні записи в PST на основі заданого критерію пошуку. У PST можна шукати повідомлення за параметрами пошуку, такими як відправник, одержувач, тема, важливість повідомлення, наявність вкладень, розмір повідомлення та навіть ID повідомлення. PersonalStorageQueryBuilder також можна використати для пошуку підпапок.

Пошук повідомлень і папок у PST

Наступний фрагмент коду показує, як використовувати PersonalStorageQueryBuilder клас для пошуку вмісту в PST на основі різних критеріїв пошуку. Наприклад, показано пошук у 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/";

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());
}

Пошук рядка в PST з параметром ігнорування регістру

Наступний фрагмент коду показує, як шукати рядок у 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/";

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());
}

Пошук тем повідомлень за кількома ключовими словами у PST‑файлі

Ви можете використати MailQueryBuilder.or метод для пошуку повідомлень із темою, що містить принаймні одне з вказаних слів, як показано нижче:

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());
    }
}

Постраничне отримання вмісту PST‑папки

Покращуйте продуктивність вашого застосунку та контроль під час навігації великими папками. Отримуйте вміст папки посторінковим способом, використовуючи перевантаження Aspose.Email для getContents метод. Цей метод - FolderInfo.getContents(MailQuery query, int startIndex, int count) - отримує підмножину повідомлень, що відповідають вказаному запиту, починаючи з заданого індексу та обмежену кількістю. Наступний приклад коду демонструє постраничне отримання та обробку відфільтрованих повідомлень з 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());
        }
    }
}

Переміщення елементів у інші папки PST‑файлу

Aspose.Email дозволяє переміщати елементи з вихідної папки в іншу папку в тому ж файлі Personal Storage (PST). Це включає:

  • Переміщення вказаної папки у нову батьківську папку.
  • Переміщення вказаного повідомлення у нову папку.
  • Переміщення вмісту у нову папку.
  • Переміщення підпапок у нову батьківську папку.

Наступний фрагмент коду показує, як перемістити елементи, такі як повідомлення та папки, з вихідної папки в іншу папку в тому ж 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);
}

Оновлення властивостей повідомлень у PST‑файлі

Іноді потрібно оновити певні властивості повідомлень, наприклад, змінити тему, позначити важливість повідомлення тощо. Оновлення повідомлення у PST файлі з такими змінами у властивостях повідомлення можна здійснити за допомогою FolderInfo.changeMessages метод. У цій статті показано, як масово оновлювати повідомлення у PST файлі щодо змін у властивостях. Нижче наведений фрагмент коду демонструє, як оновити властивості повідомлень у масовому режимі для декількох повідомлень у 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);

Оновлення користувацьких властивостей у PST файлі

Іноді необхідно позначати елементи, які були оброблені у PST файлі. API Aspose.Email дозволяє це зробити за допомогою MapiProperty та MapiNamedProperty. Наступні методи корисні для цього.

  • constructor MapiNamedProperty(long propertyTag, String nameIdentifier, UUID propertyGuid, byte[] propertyValue)
  • constructor MapiNamedProperty(long propertyTag, long nameIdentifier, UUID propertyGuid, byte[] propertyValue)
  • FolderInfo.changeMessages(MapiPropertyCollection updatedProperties) - changes all messages in folder
  • PersonalStorage.changeMessage(String entryId, MapiPropertyCollection updatedProperties) - change message properties
// 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;
}

Витягнути вкладення без повного витягнення повідомлення

API Aspose.Email можна використати для витягування вкладень з PST повідомлень без попереднього повного витягування повідомлення. Цей ExtractAttachments метод PersonalStorage можна використати для цього. Нижче наведений фрагмент коду показує, як витягнути вкладення без повного витягування повідомлення.

// 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());
                    }
                }
            }
        }
    }
}

Додавання файлів до PST

Основна функціональність Microsoft Outlook – управління електронною поштою, календарями, завданнями, контактами та записами журналу. Крім того, файли також можна додавати до папки PST, і створений PST зберігає записи доданих документів. Aspose.Email забезпечує можливість додавати файли у папку так само, як і повідомлення, контакти, завдання та записи журналу до PST. Нижче наведений фрагмент коду показує, як додати документи до папки PST за допомогою 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);
}