Đọc tệp đính kèm email nhúng từ tin nhắn trong Aspose.Email

Aspose.Email - Đọc các tệp đính kèm email nhúng từ tin nhắn

Đôi khi, chúng ta nhận được email có các email khác được nhúng trong đó như các tệp đính kèm. Những email được nhúng này là các tin nhắn đầy đủ với danh sách người nhận, tiêu đề, nội dung và thậm chí các tệp đính kèm riêng. Mỗi tin nhắn này cũng có thể chứa các tin nhắn nhúng. Sử dụng Aspose.Email Java, các nhà phát triển có thể truy cập từng tin nhắn nhúng như một tin nhắn riêng lẻ. Ví dụ này trình bày cách sử dụng chức năng đệ quy.

Java

 MailMessage message = MailMessage.load(dataDir + \"embedded.msg\", MessageFormat.getMsg());

for (int i = 0; i < message.getAttachments().size(); i++)

{

    Attachment att = (Attachment) message.getAttachments().get_Item(i);

    System.out.println("Attachment Name: " + att.getName());

    // Get the name of attachment. If msg subject contains characters like :, /, \ etc., replace with space

    // because windows cannot save files with these characters

    // also save first 50 characters as file name to avoid long file names

    String attFileName = att.getName().replace(".eml", "").replace(":", " ").replace("\\", " ").replace("/", " ").replace("?", "");

    if (attFileName.length() > 50)

    {

        attFileName = attFileName.substring(0, 50);

    }

    String attExt = (att.getName().substring(att.getName().lastIndexOf("."), att.getName().lastIndexOf(".") + 4));

    // Save the attachment to disk

    att.save(dataPath + attFileName + attExt);

    // Check if it is an orphaned text attachment file (ATT00001.txt....) and of type eml

    if ((attExt.equals(".eml")) || (att.getContentType().getMediaType().equals("text/plain") && att.getName().contains(".txt") == true && att.getName().contains("ATT") == true))

    {

        // Try to load this text file in MailMessage

        MailMessage attMsg = MailMessage.load(dataPath + attFileName + attExt, MessageFormat.getEml());

        // Call the function recursively to parse this message and attachments

        ParseMessage(attMsg);

    }

}

Tải mã đang chạy

Tải mã mẫu