Работа с сообщениями в PST‑файле
Добавление сообщений в файлы PST
Создать новый файл PST и добавить подпапки показали, как создать файл PST и добавить к нему подпапку. С помощью Aspose.Email вы можете добавлять сообщения в подпапки файла PST, который вы создали или загрузили. В этой статье добавляются два сообщения с диска в подпапку Inbox PST. Используйте PersonalStorage и FolderInfo классы для добавления сообщений в файлы PST. Чтобы добавить сообщения в папку Inbox файла PST:
- Создайте экземпляр класса FolderInfo и загрузите его содержимым папки Inbox.
- Добавьте сообщения с диска в папку 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 пакетно, минимизируя операции ввода‑вывода. Метод addMessages(Iterable
Загрузка сообщений с диска
Следующий фрагмент кода показывает, как загрузить сообщения с диска.
// 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
Следующий фрагмент кода показывает, как создать реализацию 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
// 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:
- Создать экземпляр FolderInfo класс и загрузив его содержимым подпапки Sent.
- Удалите сообщения из папки 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, переместив её в папку Deleted Items.
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());
При необходимости вы также можете окончательно удалить папку из папки Deleted Items.
deletedItemsFolder.deleteChildItem(emptyFolder.getEntryId());
Этот deleteChildItem() метод может использоваться для любых папок, если вы хотите немедленно и окончательно удалить подпапку, обходя папку Deleted Items.
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. Мягко удалённые элементы — это сообщения, удалённые дважды: сначала перемещены в папку Deleted Items, затем оттуда удалены. Эти сообщения всё ещё восстанавливаемы, и 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) - изменяет все сообщения в папке
- PersonalStorage.changeMessage(String entryId, MapiPropertyCollection updatedProperties) - изменить свойства сообщения
// 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);
}