Tải, Xem và Phân tích tệp MSG

Chủ đề này giải thích cách tải tệp tin Nhắn Microsoft Outlook (*.msg). MapiMessage lớp được sử dụng để tải các tệp MSG và cung cấp một số hàm tải tĩnh cho các kịch bản khác nhau. Đoạn mã sau đây cho bạn thấy cách tải các tệp MSG từ tệp hoặc từ luồng.

Tải các Tệp MSG

Đoạn mã sau đây cho bạn thấy cách tải các tệp MSG.

// 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 = "outlook/";

// Create an instance of MapiMessage from file
MapiMessage msg = MapiMessage.load(dataDir + "message.msg");

// Get subject
System.out.println("Subject:" + msg.getSubject());

// Get from address
System.out.println("From:" + msg.getSenderEmailAddress());

// Get body
System.out.println("Body" + msg.getBody());

// Get recipients information
System.out.println("Recipient: " + msg.getRecipients());

// Get attachments
for (MapiAttachment att : msg.getAttachments())
{
    System.out.println("Attachment Name: " + att.getFileName());
    System.out.println("Attachment Display Name: " + att.getDisplayName());
}

Ví dụ mã sau đây cho thấy cách sử dụng MailMessage để tải một tin nhắn ở định dạng MSG.

MailMessage eml = MailMessage.load("message.msg");

Cần lưu ý rằng tin nhắn đầu ra sẽ được chuyển đổi sang định dạng EML, bao gồm các tệp đính kèm tin nhắn nhúng. Không sử dụng phương pháp tải này nếu bạn muốn giữ một số thuộc tính định dạng msg cụ thể của tin nhắn gốc.

Để giữ nguyên định dạng gốc của các tệp đính kèm tin nhắn nhúng, sử dụng MsgLoadOptions.PreserveEmbeddedMessageFormat thuộc tính.

MsgLoadOptions msgLoadOptions = new MsgLoadOptions();
msgLoadOptions.setPreserveEmbeddedMessageFormat(true);
MailMessage msg = MailMessage.load(stream, msgLoadOptions);

Tải từ Luồng

Đoạn mã sau đây cho bạn thấy cách tải một tệp từ luồng.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Create an instance of MapiMessage from file
try (FileInputStream stream = new FileInputStream(dataDir + "message.msg"))
{
    // Create an instance of MapiMessage from file
    MapiMessage msg = MapiMessage.load(stream);

    // Get subject
    System.out.println("Subject:" + msg.getSubject());

    // Get from address
    System.out.println("From:" + msg.getSenderEmailAddress());

    // Get body
    System.out.println("Body" + msg.getBody());

}

Tải Tệp MSG mà không Đọc Nội Dung Đính Kèm

Mặc định, MapiMessage.load đọc nội dung của mọi đính kèm vào bộ nhớ cùng với tin nhắn. Đối với tin nhắn có đính kèm lớn, bộ nhớ cần thiết để mở tin nhắn sẽ tăng theo kích thước của các đính kèm, ngay cả khi bạn chỉ cần tiêu đề, người nhận, hoặc tên đính kèm.

Với tải trì hoãn, nội dung đính kèm ở lại trong nguồn và chỉ được đọc khi bạn truy cập. Kích hoạt nó bằng các thuộc tính sau của MsgLoadOptions lớp:

  • setDeferAttachmentContent(boolean) - khi true, nội dung đính kèm được đọc từ nguồn khi cần thay vì tải cùng tin nhắn. Mặc định là false.
  • setDeferralThreshold(int) - kích thước nội dung tối thiểu, tính bằng byte, mà việc tải trì hoãn áp dụng. Các tệp đính kèm nhỏ hơn luôn được tải cùng tin nhắn. Mặc định là 4096.

Tải hoãn áp dụng cho nội dung đính kèm nhị phân. Các tệp đính kèm được lưu dưới dạng đối tượng OLE hoặc tin nhắn nhúng sẽ được giải nén khi tin nhắn được tải.

Đoạn mã sau kiểm tra một tin nhắn mà không đọc các đính kèm của nó:

MsgLoadOptions options = new MsgLoadOptions();
options.setDeferAttachmentContent(true);

// The file stays open until the message is disposed
try (MapiMessage msg = MapiMessage.load("large.msg", options)) {
    System.out.println("Subject: " + msg.getSubject());
    System.out.println("Recipients: " + msg.getRecipients().size());

    for (MapiAttachment attachment : msg.getAttachments()) {
        // Names and sizes are available without reading the content
        System.out.println("  " + attachment.getLongFileName() + " : " + attachment.getContentLength() + " bytes");
    }
}

Đoạn mã sau chỉ trích xuất các đính kèm PDF của một tin nhắn. Nội dung các đính kèm khác không bao giờ được đọc từ tệp:

MsgLoadOptions options = new MsgLoadOptions();
options.setDeferAttachmentContent(true);

try (MapiMessage msg = MapiMessage.load("large.msg", options)) {
    for (MapiAttachment attachment : msg.getAttachments()) {
        if (!attachment.getLongFileName().endsWith(".pdf")) {
            continue;
        }

        try (InputStream source = attachment.openRead()) {
            Files.copy(source, Paths.get("out", attachment.getLongFileName()), StandardCopyOption.REPLACE_EXISTING);
        }
    }
}

Đoạn mã sau tải một tin nhắn từ luồng do người gọi sở hữu:

MsgLoadOptions options = new MsgLoadOptions();
options.setDeferAttachmentContent(true);

// Keep the stream open while the message is in use
try (InputStream source = Files.newInputStream(Paths.get("large.msg"))) {
    MapiMessage msg = MapiMessage.load(source, options);
    byte[] data = msg.getAttachments().get(0).getBinaryData();
    System.out.println("Read " + data.length + " bytes");
}

Để đọc nội dung đính kèm dưới dạng luồng và thêm đính kèm lớn mà không tải chúng vào bộ nhớ, xem Làm việc với Đính Kèm Tin Nhắn.

Chuyển đổi EML sang MSG giữ Định dạng EML Nhúng

Các tệp EML có thể được tải vào MapiMessage lớp bằng cách khởi tạo một MailMessage đối tượng và truyền nó tới MapiMessage.fromMailMessage phương thức. Nếu tệp EML chứa các tệp EML nhúng, hãy sử dụng MapiConversionOptions.setPreserveEmbeddedMessageFormat để giữ nguyên định dạng của các tệp EML nhúng. Đoạn mã dưới đây cho thấy cách tải các tệp EML vào MapiMessage trong khi giữ nguyên định dạng của các tệp EML nhúng.

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

MailMessage eml = MailMessage.load(dataDir + "sample.eml", new EmlLoadOptions());

MapiConversionOptions options = MapiConversionOptions.getUnicodeFormat();

//Preserve Embedded Message Format
options.setPreserveEmbeddedMessageFormat(true);

//Convert EML to MSG with Options
MapiMessage msg = MapiMessage.fromMailMessage(eml, options);