Làm việc với Tin nhắn trong tệp PST

Thêm Tin Nhắn vào Tệp PST

Tạo Tệp PST Mới và Thêm Thư Mục Con đã cho thấy cách tạo tệp PST và thêm một thư mục con vào đó. Với Aspose.Email bạn có thể thêm tin nhắn vào các thư mục con của tệp PST mà bạn đã tạo hoặc tải. Bài viết này thêm hai tin nhắn từ đĩa vào thư mục con Inbox của PST. Sử dụng PersonalStorageFolderInfo các lớp để thêm tin nhắn vào tệp PST. Để thêm tin nhắn vào thư mục Inbox của tệp PST:

  1. Tạo một thể hiện của lớp FolderInfo và tải nội dung của thư mục Inbox vào.
  2. Thêm tin nhắn từ đĩa vào thư mục Inbox bằng cách gọi FolderInfo.addMessage() phương thức. Thuộc tính FolderInfo lớp này cung cấp addMessages phương thức cho phép thêm một số lượng lớn tin nhắn vào thư mục, giảm các thao tác I/O tới đĩa và cải thiện hiệu suất. Một ví dụ hoàn chỉnh có thể được tìm thấy bên dưới, trong Thêm Tin Nhắn Bulk.

Các đoạn mã dưới đây cho thấy cách thêm tin nhắn vào thư mục con PST có tên 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"));

Thêm Tin Nhắn Bulk

Thêm các tin nhắn riêng lẻ vào PST đồng nghĩa với nhiều thao tác I/O tới đĩa hơn và do đó có thể làm chậm hiệu suất. Để cải thiện hiệu suất, các tin nhắn có thể được thêm vào PST ở chế độ bulk để giảm thiểu các thao tác I/O. The addMessages(Iterable messages) phương thức cho phép bạn xác định một phạm vi tin nhắn để thêm vào PST nhằm cải thiện hiệu suất và có thể được sử dụng trong các kịch bản sau. Ngoài ra, sự kiện MessageAdded xảy ra khi một tin nhắn được thêm vào thư mục.

Tải Tin Nhắn Từ Đĩa

Đoạn mã dưới đây cho bạn thấy cách tải tin nhắn từ đĩa.

// 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 Implementation

Đoạn mã dưới đây cho bạn thấy cách tạo Iterable Implementation.

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

Thêm tin nhắn từ PST khác

Để thêm tin nhắn từ PST khác, sử dụng FolderInfo.enumerateMapiMessages() phương thức trả về Iterable. Đoạn mã dưới đây cho bạn thấy cách thêm tin nhắn từ PST khác.

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

Lấy thông tin tin nhắn từ tệp Outlook PST

Trong Đọc Tệp Outlook PST và Lấy Thông Tin Thư Mục và Thư Mục Con, chúng tôi đã thảo luận về việc tải tệp Outlook PST và duyệt các thư mục để lấy tên thư mục và số lượng tin nhắn trong chúng. Bài viết này giải thích cách đọc tất cả các thư mục và thư mục con trong tệp PST và hiển thị thông tin về các tin nhắn, ví dụ: tiêu đề, người gửi và người nhận. FolderInfo.getContents() phương thức được sử dụng để hiển thị thông tin tin nhắn ngắn gọn như tiêu đề, người gửi, người nhận. Về hiệu năng, đây là lựa chọn phù hợp nhất để lấy thông tin chính về các tin nhắn. Để trích xuất dữ liệu tin nhắn đầy đủ, PersonalStorage.extractMessage() phương thức được cung cấp. Tệp Outlook PST có thể chứa các thư mục lồng nhau. Để lấy thông tin tin nhắn từ chúng, cũng như các thư mục cấp cao nhất, hãy sử dụng phương pháp đệ quy để đọc tất cả các thư mục. Đoạn mã dưới đây cho bạn thấy cách đọc tệp Outlook PST và hiển thị nội dung thư mục và tin nhắn một cách đệ quy.

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

Trích xuất tin nhắn từ tệp PST

Bài viết này chỉ cách đọc các tệp Microsoft Outlook PST và trích xuất tin nhắn. Các tin nhắn sau đó được lưu vào đĩa ở định dạng MSG. Bài viết cũng chỉ cách trích xuất một số lượng tin nhắn cụ thể từ tệp PST. Sử dụng phương pháp đệ quy để duyệt tất cả các thư mục (gồm các thư mục lồng nhau) và gọi PersonalStorage.extractMessage() phương thức để lấy các tin nhắn Outlook vào một thể hiện của MapiMessage lớp. Sau đó, gọi MapiMessage.save() phương thức để lưu tin nhắn vào đĩa hoặc stream ở định dạng MSG. Đoạn mã dưới đây cho bạn thấy cách trích xuất tin nhắn từ tệp 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);
        }
    }
}

Lưu tin nhắn trực tiếp từ PST tới Stream

Để lưu tin nhắn từ tệp PST trực tiếp vào stream, mà không cần trích xuất MsgInfo cho các tin nhắn, hãy sử dụng saveMessageToStream() phương thức. Đoạn mã dưới đây cho bạn thấy cách lưu tin nhắn trực tiếp từ PST tới stream.

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

Trích xuất n số tin nhắn từ tệp PST

Đoạn mã dưới đây cho bạn thấy cách trích xuất một số lượng tin nhắn nhất định từ PST. Chỉ cần cung cấp chỉ mục cho tin nhắn đầu tiên và tổng số tin nhắn cần trích xuất.

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

Lấy tổng số mục từ tệp PST

Aspose.Email cung cấp GetTotalItemsCount() phương thức của PersonalStorage.Store thuộc tính. Nó trả về tổng số mục tin nhắn chứa trong PST.

Đoạn mã mẫu dưới đây cho thấy cách lấy tổng số lượng các mục (tin nhắn, cuộc hẹn, danh bạ, v.v.) được lưu trong tệp PST:

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

Xóa các mục khỏi tệp PST

Thêm tin nhắn vào tệp PST đã cho thấy cách thêm tin nhắn vào tệp PST. Tất nhiên, cũng có thể xóa các mục (nội dung) khỏi tệp PST và cũng có thể muốn xóa tin nhắn hàng loạt. Các mục từ tệp PST có thể được xóa bằng cách sử dụng FolderInfo.deleteChildItem() phương thức. API cũng cung cấp FolderInfo.deleteChildItems() phương thức để xóa các mục hàng loạt từ tệp PST.

Xóa tin nhắn khỏi tệp PST

Bài viết này cho biết cách sử dụng FolderInfo lớp để truy cập các thư mục cụ thể trong tệp PST. Để xóa tin nhắn từ thư mục Con Đã Gửi của tệp PST đã được tải trước hoặc đã tạo:

  1. Tạo một đối tượng của FolderInfo lớp và tải nó với nội dung của thư mục con đã gửi.
  2. Xóa tin nhắn từ thư mục Đã Gửi bằng cách gọi FolderInfo.deleteChildItem() phương thức và truyền MessageInfo.EntryId là một tham số. Đoạn mã dưới đây cho bạn thấy cách xóa tin nhắn từ thư mục Con Đã Gửi của tệp 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");
    }
}

Xóa thư mục khỏi tệp PST

Bạn có thể xóa thư mục PST bằng cách chuyển nó tới thư mục Đã Xóa.

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

Ưu điểm của phương pháp này là thư mục đã xóa có thể được khôi phục dễ dàng.

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

Bạn cũng có thể xóa vĩnh viễn một thư mục khỏi thư mục Đã Xóa, nếu cần.

deletedItemsFolder.deleteChildItem(emptyFolder.getEntryId());

Cái deleteChildItem() phương thức có thể được sử dụng cho bất kỳ thư mục nào nếu bạn muốn xóa ngay lập tức và vĩnh viễn thư mục con, bỏ qua thư mục Đã Xóa.

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

Xóa các mục hàng loạt từ tệp PST

API Aspose.Email có thể được sử dụng để xóa các mục hàng loạt từ tệp PST. Điều này được thực hiện bằng cách sử dụng deleteChildItems() phương thức nhận một danh sách các mục Entry ID đề cập đến các mục cần xóa. Đoạn mã dưới đây cho bạn thấy cách xóa các mục hàng loạt từ tệp 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);
}

Liệt kê và khôi phục các tin nhắn đã xóa mềm từ PST

Có thể truy xuất các tin nhắn đã xóa vĩnh viễn bằng Aspose.Email cho Java. API của nó cho phép liệt kê các tin nhắn đã xóa mềm trong tệp PST. Các mục đã xóa mềm là những tin nhắn bị xóa hai lần - đầu tiên được chuyển tới thư mục Đã Xóa và sau đó được xóa khỏi đó. Những tin nhắn này vẫn có thể khôi phục, và Aspose.Email cung cấp cách tiện lợi để truy cập chúng. PersonalStorage.findAndEnumerateSoftDeletedItems() phương thức trả về một tập hợp các RestoredItemEntry đối tượng. Mỗi mục nhập chứa:

  • MapiMessage mục — tin nhắn đã khôi phục.
  • String FolderId - định danh của thư mục mà tin nhắn ban đầu thuộc về.

Đoạn mã mẫu dưới đây minh họa cách liệt kê các mục email đã xóa mềm (có thể khôi phục) trong tệp 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("-----------------------------------");
    }
}

Tìm kiếm tin nhắn và thư mục trong PST theo tiêu chí

Các tệp Personal Storage (PST) có thể chứa một lượng dữ liệu khổng lồ và việc tìm kiếm dữ liệu đáp ứng một tiêu chí cụ thể trong các tệp lớn như vậy cần bao gồm nhiều điểm kiểm tra trong mã để lọc thông tin. Với PersonalStorageQueryBuilder lớp, Aspose.Email cho phép tìm kiếm các bản ghi cụ thể trong PST dựa trên tiêu chí tìm kiếm được chỉ định. Một PST có thể được tìm kiếm các tin nhắn dựa trên các tham số như người gửi, người nhận, tiêu đề, mức độ quan trọng, có tệp đính kèm, kích thước tin nhắn và thậm chí ID tin nhắn. PersonalStorageQueryBuilder cũng có thể được sử dụng để tìm các thư mục con.

Tìm kiếm tin nhắn và thư mục trong PST

Đoạn mã sau cho bạn thấy cách sử dụng PersonalStorageQueryBuilder lớp để tìm nội dung trong PST dựa trên các tiêu chí tìm kiếm khác nhau. Ví dụ, nó minh họa việc tìm kiếm PST dựa trên:

  • Mức độ quan trọng của tin nhắn.
  • Lớp tin nhắn.
  • Có tệp đính kèm.
  • Kích thước tin nhắn.
  • Ngày tin nhắn.
  • Tin chưa đọc.
  • Tin chưa đọc có tệp đính kèm, và
  • các thư mục có tên thư mục con cụ thể.
// 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());
}

Tìm kiếm một chuỗi trong PST với tham số bỏ qua chữ hoa chữ thường

Đoạn mã dưới đây cho bạn thấy cách tìm kiếm một chuỗi trong PST với tham số bỏ qua chữ hoa chữ thường.

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

Tìm kiếm tiêu đề tin nhắn bằng nhiều từ khóa trong tệp PST

Bạn có thể sử dụng MailQueryBuilder.or phương thức để tìm các tin nhắn có tiêu đề chứa ít nhất một trong các từ được chỉ định như dưới đây:

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

Truy xuất có phân trang nội dung thư mục PST

Cải thiện hiệu năng ứng dụng và kiểm soát khi duyệt các thư mục lớn. Truy xuất nội dung thư mục theo cách phân trang bằng cách sử dụng overload của Aspose.Email cho getContents phương thức. Phương thức này - FolderInfo.getContents(MailQuery query, int startIndex, int count) - truy xuất một tập hợp con các tin nhắn khớp với truy vấn được chỉ định, bắt đầu từ chỉ mục cho trước và giới hạn bởi số lượng. Đoạn mã mẫu dưới đây minh họa việc truy xuất có phân trang và xử lý các tin nhắn đã lọc từ một thư mục 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());
        }
    }
}

Di chuyển các mục tới các thư mục khác của tệp PST

Aspose.Email cho phép di chuyển các mục từ thư mục nguồn sang một thư mục khác trong cùng tệp Personal Storage (PST). Điều này bao gồm:

  • Di chuyển một thư mục được chỉ định đến một thư mục cha mới.
  • Di chuyển một tin nhắn được chỉ định đến một thư mục mới.
  • Di chuyển nội dung đến một thư mục mới.
  • Di chuyển các thư mục con đến một thư mục cha mới.

Đoạn mã dưới đây cho bạn thấy cách di chuyển các mục như tin nhắn và thư mục từ thư mục nguồn sang một thư mục khác trong cùng tệp 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);
}

Cập nhật thuộc tính tin nhắn trong tệp PST

Đôi khi cần cập nhật một số thuộc tính của tin nhắn như thay đổi tiêu đề, đánh dấu tầm quan trọng tin nhắn và các thứ tương tự. Việc cập nhật tin nhắn trong tệp PST, với các thay đổi như vậy trong thuộc tính tin nhắn, có thể thực hiện bằng cách sử dụng FolderInfo.changeMessages phương thức. Bài viết này cho thấy cách cập nhật hàng loạt tin nhắn trong tệp PST cho các thay đổi thuộc tính. Đoạn mã mẫu dưới đây cho bạn thấy cách cập nhật thuộc tính của tin nhắn trong chế độ hàng loạt cho nhiều tin nhắn trong tệp 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);

Cập nhật Thuộc tính Tùy chỉnh trong tệp PST

Đôi khi cần đánh dấu các mục đã được xử lý trong tệp PST. API Aspose.Email cho phép thực hiện điều này bằng cách sử dụng MapiProperty và MapiNamedProperty. Các phương thức sau hữu ích cho việc này.

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

Trích xuất Tệp đính kèm mà không Trích xuất Toàn bộ Tin nhắn

API Aspose.Email có thể được sử dụng để trích xuất tệp đính kèm từ tin nhắn PST mà không cần trích xuất toàn bộ tin nhắn trước. Các ExtractAttachments phương thức của PersonalStorage có thể được sử dụng để thực hiện điều này. Đoạn mã mẫu dưới đây cho bạn thấy cách trích xuất tệp đính kèm mà không cần trích xuất toàn bộ tin nhắn.

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

Thêm Tệp vào PST

Chức năng chính của Microsoft Outlook là quản lý email, lịch, công việc, liên hệ và mục nhật ký. Ngoài ra, các tệp cũng có thể được thêm vào thư mục PST và PST kết quả sẽ ghi lại các tài liệu đã thêm. Aspose.Email cung cấp khả năng thêm tệp vào thư mục theo cách tương tự như việc thêm tin nhắn, liên hệ, công việc và mục nhật ký vào PST. Đoạn mã mẫu dưới đây cho bạn thấy cách thêm tài liệu vào thư mục PST bằng 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);
}