Outlook PST からメッセージを抽出し MSG に保存する
Contents
[
Hide
]
この移行ヒントでは、Outlook PST ファイルからメッセージを抽出し、MSG ファイルとしてディスクに保存する方法を示します。いくつかの手順が含まれます:
- Outlook PST ファイルを読み取ります、
- メッセージを抽出し、最終的に
- 抽出したメッセージを保存します。
同じ結果を得る方法は複数あります: この記事では VSTO と Aspose.Email の使用を比較しています。まずは、 Microsoft Office Interop を使用するコードサンプル PST からメッセージを抽出するために。この例の後、 コードサンプルは Aspose.Email Outlook の使用方法を示します、Java で同じタスクを実行するために。
Microsoft Office Interop の使用
Microsoft Outlook 用の Office Automation オブジェクトを使用するには、プロジェクトに Microsoft Office Interop for Outlook ライブラリへの参照を追加します。また、コードが実行されるマシンに Microsoft Office Outlook がインストールされている必要があります。以下のコードサンプルで使用されている名前空間は Microsoft.Office.Interop.Outlook です。
プログラミング例
C#
string pstFilePath = @"C:\sample.pst";
Application app = new Application();
NameSpace outlookNs = app.GetNamespace("MAPI");
// Add PST file (Outlook Data File) to Default Profile
outlookNs.AddStore(pstFilePath);
MAPIFolder rootFolder = outlookNs.Stores["items"].GetRootFolder();
// Traverse through all folders in the PST file
// TODO: This is not recursive
Folders subFolders = rootFolder.Folders;
foreach (Folder folder in subFolders)
{
Items items = folder.Items;
foreach (object item in items)
{
if (item is MailItem)
{
// Retrieve the Object into MailItem
MailItem mailItem = item as MailItem;
Console.WriteLine("Saving message {0} ....", mailItem.Subject);
// Save the message to disk in MSG format
// TODO: File name may contain invalid characters [\ / : * ? " < > |]
mailItem.SaveAs(@"\extracted\" + mailItem.Subject + ".msg",OlSaveAsType.olMSG);
}
}
}
// Remove PST file from Default Profile
outlookNs.RemoveStore(rootFolder);
Aspose.Email の使用
以下のコードスニペットは、次と同じことを行います: 上記のコード しかし Aspose.Email を使用します。Aspose.Email for Java がインストールされていれば、マシンに Microsoft Outlook は不要です。プロジェクトをビルドおよび実行するために Aspose.Email を参照するだけです。
プログラミングサンプル
String pstFilePath = "C:\\sample.pst";
// Create an instance of PersonalStorage and load the PST from file
try (PersonalStorage personalStorage = PersonalStorage.fromFile(pstFilePath)) {
// Get the list of subfolders in PST file
FolderInfoCollection folderInfoCollection = personalStorage.getRootFolder().getSubFolders();
// Traverse through all folders in the PST file
// This is not recursive
for (FolderInfo folderInfo : folderInfoCollection) {
// Get all messages in this folder
MessageInfoCollection messageInfoCollection = folderInfo.getContents();
// Loop through all the messages in this folder
for (MessageInfo messageInfo : messageInfoCollection) {
// Extract the message in MapiMessage instance
MapiMessage message = personalStorage.extractMessage(messageInfo);
System.out.println("Saving message " + message.getSubject() + " ...");
// Save the message to disk in MSG format
// TODO: File name may contain invalid characters [\ / : * ? " < > |]
message.save("\\extracted\\" + message.getSubject() + ".msg");
}
}
}