メッセージの添付ファイルの操作

添付ファイルの解析と保存

Outlook メッセージファイルは 1 つ以上の添付ファイルを含むことがあります。Aspose.Email は開発者が MSG ファイル内の添付ファイルをループ処理し、ディスクに保存できるようにします。本項ではその手順を説明し、添付ファイルを埋め込む方法も紹介します。

Aspose.Email MapiMessage このクラスはディスクから MSG ファイルを読み込み、… を提供します。 getAttachments() 参照するメソッド MapiAttachment MSG ファイルに関連付けられたオブジェクトコレクションです。 MapiAttachment オブジェクトはさらに、添付ファイルに対する操作を行うメソッドを公開します。

元の名前と拡張子で MSG ファイルの添付ファイルをディスクに保存するには:

  1. インスタンスを作成します MapiMessage クラスは、次を使用して MSG ファイルをロードします Load() 静的メソッド。
  2. 呼び出す MapiRecipient クラス getAttachments() コレクションへの参照を取得するメソッド MapiAttachment MSG ファイルに関連付けられたオブジェクト。
  3. ループで回す MapiAttachmentCollection 各…の内容を表示するために MapiAttachment オブジェクトの公開メソッドを通じて。
  4. 呼び出す MapiAttachment クラス save() 添付ファイルをディスクに保存するメソッド。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";

// Load an MSG file from disk
MapiMessage outlookMessageFile = MapiMessage.load(dataDir + "WithEmbeddedMsg.msg");

// Loop through the attachments collection of the MapiMessage object
for (MapiAttachment attachment : outlookMessageFile.getAttachments()) {
    // Display the attachment type
    System.out.println("Att Type : " + attachment.getMimeTag());

    // Display the attached file name
    System.out.println("File Name : " + attachment.getLongFileName());

    // Save the attachment to disk
    attachment.save(dataDir + attachment.getDisplayName());
}

メッセージの添付としての埋め込み

Microsoft Outlook メッセージは、添付ファイルとして他の Outlook メッセージを、上記の通常メッセージまたは埋め込みメッセージとして含めることができます。The MapiAttachmentCollection Outlook の添付ファイルの両タイプで Outlook メッセージを作成するための add メソッドのオーバーロードを提供します。MSG ファイルに埋め込まれた Outlook MSG ファイルには、値 5 の PR_ATTACH_METHOD が含まれます。

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";

MapiMessage msg = new MapiMessage("from@test.com", "to@test.com", "Subj", "This is a message body");

MapiMessage attachMsg = MapiMessage.load(dataDir + "message.msg");
msg.getAttachments().add("Weekly report", attachMsg);

msg.save(dataDir + "EmbeddedMessageAsAttachment.msg");

添付ファイルから埋め込みメッセージを読み取る

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";

MapiMessage mapi = MapiMessage.load(dataDir + "EmbeddedMessageAsAttachment.msg");

MapiMessage embedded = mapi.getAttachments().get_Item(0).getObjectData().toMapiMessage();
System.out.println("Embedded subject: " + embedded.getSubject());

MSG 添付ファイルを追加

Outlookメッセージは、通常の添付ファイルまたは埋め込みメッセージとして、他のMicrosoft Outlookメッセージを含めることができます。The MapiAttachmentCollection のオーバーロードされたメンバーを提供します。 add 両方のタイプの添付ファイルを持つ Outlook メッセージを作成するメソッド:

  • add(String name, byte[] data) — バイト配列から通常の添付ファイルを追加します。
  • add(String name, MapiMessage message) — 別のOutlookメッセージを埋め込みメッセージとして追加します。

以下のコードスニペットは、メッセージに両方のタイプの添付ファイルを追加する方法を示しています。

MapiMessage message = new MapiMessage("from@test.com", "to@test.com", "Subj", "This is a message body");

// Add a regular attachment from a byte array
message.getAttachments().add("note.txt", Files.readAllBytes(Paths.get("note.txt")));

// Add another Outlook message as an embedded message
MapiMessage attachMsg = MapiMessage.load("Message.msg");
message.getAttachments().add("Weekly report.msg", attachMsg);

message.save("WithAttachments_out.msg");

新しく追加された添付ファイルへのアクセス

この add のメソッド MapiAttachmentCollection クラスは MapiAttachment オブジェクトを作成します。これにより新しい添付ファイルにすぐにアクセスでき、コレクションを検索せずに挿入直後に設定できます。次のオーバーロードは作成された添付ファイルを返します:

次のコードスニペットは添付ファイルを追加し、表示名を変更します:

MapiMessage message = new MapiMessage("from@domain.com", "to@domain.com", "Invoice", "Please find the invoice attached.");

MapiAttachment attachment = message.getAttachments().add("invoice.pdf", Files.readAllBytes(Paths.get("invoice.pdf")));
attachment.setDisplayName("Invoice #2026-001.pdf");

message.save("invoice.msg");

ストリームまたはファイルから添付ファイルを追加する

バイト配列から添付ファイルを追加する場合、コンテンツ全体をメモリに保持する必要があります。大きなファイルは、ストリームとしてコンテンツを供給するか、直接ファイルから取得してください。コンテンツはメッセージ保存時にオンデマンドで読み込まれ、全体がメモリにコピーされることはありません。その MapiAttachmentCollection クラスはこれに対して次のメソッドを提供します:

  • add(String name, InputStream content) - ストリームからコンテンツを読み取り、現在位置から末尾までの添付ファイルを追加します。ストリームは引き続き制御下にあり、メッセージが保存されるまでオープンしたままである必要があります。
  • addFile(String filePath) - ファイルから添付ファイルを追加し、ファイル名を添付名として使用します。
  • addFile(String filePath, String displayName) - 指定された表示名でファイルから添付ファイルを追加します。

これらすべてのメソッドは作成されたものを返します。 MapiAttachment オブジェクト。その getContentLength() メソッドは添付コンテンツのサイズ(バイト)を、コンテンツを読み取らずに返します。

次のコード スニペットは大きなファイルを添付します。コンテンツはメッセージ保存時にファイルから読み取られるため、不要になったらメッセージを破棄してください。— try-with-resources 文がこれを行います:

try (MapiMessage msg = new MapiMessage("from@domain.com", "to@domain.com", "Quarterly report", "See the archive attached.")) {
    msg.getAttachments().addFile("archive.zip");
    msg.save("report.msg");
}

次のコード スニペットは、既存のストリームから添付ファイルを追加し、そのサイズを出力します:

try (InputStream content = Files.newInputStream(Paths.get("presentation.pptx"))) {
    MapiMessage msg = new MapiMessage("from@domain.com", "to@domain.com", "Slides", "Slides attached.");
    MapiAttachment attachment = msg.getAttachments().add("presentation.pptx", content);

    // The size is known without reading the content
    System.out.println("Attachment size: " + attachment.getContentLength() + " bytes");

    // The stream must stay open until the message is saved
    msg.save("slides.msg");
}

添付コンテンツをストリームとして読み取る

この openRead() メソッド( MapiAttachment クラスは添付コンテンツへの読み取り専用ストリームを返します。これを使用して、大きな添付ファイルをバイト配列として実体化せずにコピーまたは処理できます。各呼び出しは個別の独立したストリームを返すため、複数のリーダーを同時に使用できます。

MapiMessage msg = MapiMessage.load("message.msg");

for (MapiAttachment attachment : msg.getAttachments()) {
    System.out.println(attachment.getLongFileName() + " : " + attachment.getContentLength() + " bytes");

    // Stream the content to a file instead of reading it into a byte array
    try (InputStream source = attachment.openRead()) {
        Files.copy(source, Paths.get("out", attachment.getLongFileName()), StandardCopyOption.REPLACE_EXISTING);
    }
}

添付ファイルのコンテンツを全く読み取らずにメッセージを開くには、次で説明する遅延添付ロードを使用してください MSG ファイルのロード、表示、解析.

MapiMessage に参照添付を追加

この ReferenceAttachmentOptions クラスはすべての必要プロパティを単一オブジェクトにカプセル化し、参照添付の追加を簡素化します:

  • sharedLink — ファイルをホストするウェブサービスが提供する完全修飾共有リンク;
  • url — ファイルの場所またはリソースURL;
  • providerName — 参照添付プロバイダーの名前(例: Google Drive、Dropbox)。
MapiMessage msg = MapiMessage.load("message.msg");

ReferenceAttachmentOptions options = new ReferenceAttachmentOptions(
        "https://drive.google.com/file/d/1HJ-M3F2qq1oRrTZ2GZhUdErJNy2CT3DF/",
        "https://drive.google.com/drive/my-drive",
        "GoogleDrive");

// Add the reference attachment
msg.getAttachments().add("Document.pdf", options);

msg.save("with-reference-attachment.msg");

添付タイプの確認 (IsReference)

この MapiAttachment クラスには isReference() メソッドはメッセージ内の参照添付を識別するために使用されます:

MapiMessage msg = MapiMessage.load("message.msg");

for (MapiAttachment attachment : msg.getAttachments()) {
    if (attachment.isReference()) {
        // Process the reference attachment
        System.out.println("Reference attachment: " + attachment.getLongFileName());
    }
}

入れ子メールメッセージ添付の取得

埋め込みメッセージ添付は MapiMessage クラス。 MapiMessage.fromProperties() 静的メソッドは埋め込み添付から新しいメッセージを作成します。以下のコードスニペットは、入れ子になったメールメッセージ添付を取得し、ディスクに保存する方法を示しています。

MapiMessage msg = MapiMessage.load("message.msg");

for (MapiAttachment attachment : msg.getAttachments()) {
    if (attachment.getObjectData() == null) {
        continue;
    }

    // Create a MapiMessage object from the individual attachment
    MapiMessage nested = MapiMessage.fromProperties(attachment.getObjectData().getProperties());

    // Convert the embedded message to a MailMessage and save it to disk
    MailMessage mailMessage = nested.toMailMessage(new MailConversionOptions());
    mailMessage.save("NestedMailMessageAttachments_out.eml", SaveOptions.getDefaultEml());
}

添付ファイルを削除

Aspose.EmailはMicrosoft Outlookメッセージ(.msg)ファイルから添付ファイルを削除する機能を提供します。静的 removeAttachments() メソッドはメッセージファイルのパスをパラメータとして受け取ります:

MapiMessage.removeAttachments("AttachmentsToRemove_out.msg");

静的メソッドも呼び出せます。 destroyAttachments() メソッドです。こちらの方が removeAttachments()、後者はメッセージファイルを解析します:

MapiMessage.destroyAttachments("AttachmentsToDestroy_out.msg");

添付ファイルの MSG 挿入と置換

Aspose.Email API は、親メッセージ内の特定のインデックスに添付ファイルを挿入する機能を提供します。また、添付ファイルの内容を別のメッセージ添付で置き換える機能も提供します。

特定の位置に MSG 添付を挿入

Aspose.Email API は、親 MSG に MSG 添付ファイルを挿入する機能を提供します。 MapiAttachmentCollection.Insert() メソッド。

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";

MapiMessage msg = MapiMessage.load(dataDir + "WithEmbeddedMsg.msg");
msg.getAttachments().get_Item(0).save(dataDir + "attachment_out.msg");

MapiMessage emb = MapiMessage.load(dataDir + "WithEmbeddedMsg.msg");

// Insert the message as the attachment at index 1
msg.getAttachments().insert(1, "new 11", emb);

msg.save(dataDir + "insertMSGAttachment_out.msg");

埋め込み MSG 添付内容の置換

これを使用して埋め込み添付の内容を新しいものに置き換えることができます。 置換 メソッド。ただし、PR_ATTACH_NUM = 4(例)の添付ファイルをコレクション.Count = 2 のコレクションに挿入することはできません。

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";

MapiMessage msg = MapiMessage.load(dataDir + "insertMSGAttachment_out.msg");
msg.getAttachments().get_Item(0).save(dataDir + "attachment_out.msg");

MapiMessage emb = MapiMessage.load(dataDir + "insertMSGAttachment_out.msg");

// Replace the contents of the attachment at index 1
msg.getAttachments().replace(1, "new 1", emb);

msg.save(dataDir + "replaceEmbeddedMSGAttachment_out.msg");

デジタル署名されたメッセージから添付ファイルを保存

Aspose.Email API は、クリア署名メッセージをデコードするかどうかを示す値を取得または設定する機能を提供します。

String dataDir = "data/";

MapiMessage msg = MapiMessage.load(dataDir + "signed.msg");

// The attachments of a clear-signed message are wrapped in the signature,
// so remove it first and read the attachments from the resulting message
if (msg.isSigned()) {
    SmimeResult result = new SecureEmailManager().checkSignature(msg);
    System.out.println("Signature valid: " + result.isSuccess());

    msg = msg.removeSignature();
}

for (MapiAttachment attachment : msg.getAttachments()) {
    System.out.println(attachment.getLongFileName());
    attachment.save(dataDir + attachment.getLongFileName());
}

MapiMessage の添付ファイルの名前変更

Aspose.Email は、… を編集できるようにします。 表示名 プロパティ値です MapiMessage の添付ファイル.

以下のコードサンプルは、ロードした MapiMessage 内の最初と2番目の添付ファイルの表示名を更新する方法を示します。

MapiMessage msg = MapiMessage.load(fileName);
msg.getAttachments().get_Item(0).setDisplayName("New display name 1");
msg.getAttachments().get_Item(1).setDisplayName("New display name 2");

添付ファイルがインラインか通常かを確認

インライン添付と通常添付の違いは、メール内での表示方法です。インライン添付はメール本文に埋め込まれており、別ファイルを開いたりダウンロードしたりすることなく表示できます。一方、通常添付はメール本文とは別のファイルとして添付されており、本文に直接表示されず、ダウンロードして外部で開く必要があります。 MapiAttachment.IsInline プロパティ( MapiAttachment クラスは、添付ファイルがインラインか通常かを示す値を取得します。

以下のコードサンプルは、ファイルからメールメッセージをロードし、添付ファイルの情報を取得します。具体的には、各添付ファイルの表示名とメッセージ内でインラインかどうかを出力します。

MapiMessage message = MapiMessage.load("fileName");

for (MapiAttachment attach : message.getAttachments()) {
    System.out.println(attach.getDisplayName() + ": " + attach.isInline());
}

oledata.mso から埋め込み OLE オブジェクトを抽出する

埋め込み OLE データが oledata.mso 添付ファイルは MapiAttachment と組み合わせて使用でき、手動で抽出する必要があります。これらの oledata.mso ファイルはMicrosoft Compound Document File(MCDF)形式で、Aspose.Emailの対象外です。しかし、Aspose.Emailは InlineAttachmentExtractor バイナリ データに含まれる MSO パッケージを列挙するクラスです。 oledata.mso、これをコンパウンドファイル読み取りライブラリ(例: Apache POI POIFS)コンテンツ抽出用。

メッセージ本文タイプがHTML(RTFでない)で、メッセージにOLEオブジェクトが含まれる場合、 MapiPropertyTag.PR_ATTACH_DATA_OBJ プロパティが存在しません。この場合、OLE オブジェクトに関する情報は oledata.mso.

以下のコードはMSOパッケージを列挙し、各パッケージを個別のファイルに書き出して、コンパウンドファイルリーダーで開けるようにします:

MapiMessage msg = MapiMessage.load("double.msg");

for (MapiAttachment mapiAttachment : msg.getAttachments()) {
    if (!"oledata.mso".equals(mapiAttachment.getLongFileName())) {
        continue;
    }

    com.aspose.email.system.collections.generic.IGenericDictionary<String, byte[]> oledata =
            InlineAttachmentExtractor.enumerateMsoPackage(new ByteArrayInputStream(mapiAttachment.getBinaryData()));

    int index = 0;
    for (com.aspose.email.system.collections.generic.KeyValuePair<String, byte[]> oleItem : oledata) {
        // Each value is a compound file - read its CONTENTS stream with an MCDF library,
        // or store it as is for further processing
        Files.write(Paths.get(index + ".mso"), oleItem.getValue());
        index++;
    }
}