Tính Năng Tiện Ích - MailMessage

Mã Hoá và Giải Mã Tin Nhắn

Aspose.Email cung cấp khả năng Mã hoá và Giải mã tin nhắn Email. Chủ đề này chỉ ra cách tải một tin nhắn hiện có hoặc mới và mã hoá chúng bằng cách sử dụng MailMessage. Thuộc tính encrypt() và decrypt() các phương thức trả về đối tượng MailMessage cho các hiệu ứng đã áp dụng và cần được chú ý khi mã hoá/giải mã tin nhắn. Việc mã hoá và giải mã tin nhắn bao gồm các bước sau:

  1. Tạo tin nhắn mới hoặc tải một tin nhắn hiện có
  2. Mã hoá tin nhắn bằng tệp chứng chỉ
  3. Gửi tin nhắn hoặc lưu nó
  4. Giải mã tin nhắn khi cần

Đoạn mã dưới đây cho bạn cách mã hoá và giải mã tin nhắn.

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

Path publicCertFilePath = Paths.get(dataDir + "MyKey.cer");
Path privateCertFilePath = Paths.get(dataDir + "MyPFX.pfx");

// Create a message
MailMessage msg = new MailMessage("sender@domain.com", "receiver@domain.com", "Test subject", "Test Body");

try {
    // Encrypt the message with the public certificate
    MailMessage encrypted = msg.encrypt(Files.readAllBytes(publicCertFilePath), "");
    System.out.println("Encrypted: " + encrypted.isEncrypted());

    // Decrypt it back with the private key and its password
    MailMessage decrypted = encrypted.decrypt(Files.readAllBytes(privateCertFilePath), "password");
    System.out.println("Encrypted: " + decrypted.isEncrypted());
} catch (IOException e) {
    e.printStackTrace();
}

Kiểm Tra Tin Nhắn Có Được Mã Hoá

Aspose.Email MailMessage lớp cho phép kiểm tra một tin nhắn có được mã hoá hay không. The isEncrypted thuộc tính của MailMessage cho phép kiểm tra điều này như được minh họa trong đoạn mã mẫu dưới đây.

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

Path publicCertFilePath = Paths.get(dataDir + "MyKey.cer");
Path privateCertFilePath = Paths.get(dataDir + "MyPFX.pfx");

// Load a message and check whether it is already encrypted
MailMessage originalMsg = MailMessage.load(dataDir + "Message.msg", new MsgLoadOptions());
System.out.println("Encrypted: " + originalMsg.isEncrypted());

try {
    // Encrypt the message
    MailMessage mailMsg = originalMsg.encrypt(Files.readAllBytes(publicCertFilePath), "");
    System.out.println("Encrypted: " + mailMsg.isEncrypted());

    // Decrypt the message
    mailMsg = mailMsg.decrypt(Files.readAllBytes(privateCertFilePath), "password");
    System.out.println("Encrypted: " + mailMsg.isEncrypted());
} catch (IOException e) {
    e.printStackTrace();
}

Ký và Mã hoá Tin nhắn bằng Khóa S/MIME

Aspose.Email cho Java đại diện cho một chứng chỉ, có hoặc không có khóa riêng, như một SmimeKey. Không có X509Certificate2 kiểu trong Java API: một khóa được tải từ PFX, tệp khóa riêng hoặc tệp chứng chỉ bằng các phương thức tĩnh của SmimeKey, và đối tượng đó sau đó được truyền vào các phương thức ký và mã hoá của MailMessage:

String dataDir = "data/";

MailMessage msg = new MailMessage("sender@domain.com", "receiver@domain.com", "Signed", "Body");

// A PFX holds the private key and its certificate; the password is a char array
SmimeKey key = SmimeKey.loadPFX(dataDir + "MyPFX.pfx", "password".toCharArray());

// Sign the message - pass true for a detached signature, or use attachDetachedSignature
MailMessage signed = msg.attachSignature(key);

// Encrypt with one or more recipient certificates
SmimeKey recipientCert = SmimeKey.loadCertificate(dataDir + "MyKey.cer");
MailMessage encrypted = signed.encrypt(recipientCert);

// Decrypt with the private key
MailMessage decrypted = encrypted.decrypt(key);

// Inspect the certificates of a signed message
for (java.security.cert.X509Certificate certificate : decrypted.checkSignatureCert()) {
    System.out.println(certificate.getSubjectX500Principal());
}

Cấu Hình Tùy Chọn Locale cho Aspose.Email

Bạn có thể sử dụng LocaleOptions lớp khi locale mặc định không được nhận diện, và đặt locale phù hợp nhất cho thư viện Aspose.Email. Nó cung cấp các phương thức sau:

Đoạn mã mẫu dưới đây minh họa cách tải một tin nhắn email từ tệp bằng cách sử dụng các cài đặt locale đã chỉ định:

final Locale locale = new Locale("en", "DE");
Locale.setDefault(locale);

// set Locale for Aspose Email lib
LocaleOptions.setLocale("en-US");
// or
//LocaleOptions.setLocale(new Locale("en", "US"));

MailMessage.load("document.msg");

Đoạn mã này đảm bảo rằng ứng dụng và thư viện Aspose.Email sử dụng các locale được chỉ định để xử lý ngôn ngữ, quốc gia và quy ước văn hoá.

MailMessages chứa tệp đính kèm TNEF

Transport Neutral Encapsulation Format (TNEF) là định dạng tệp đính kèm email độc quyền được sử dụng bởi Microsoft Outlook và Microsoft Exchange Server. API Aspose.Email cho phép bạn đọc các email có tệp đính kèm TNEF và chỉnh sửa nội dung của chúng. Email sau đó có thể được lưu dưới dạng email thông thường hoặc cùng định dạng, giữ lại các tệp đính kèm TNEF. Bài viết này trình bày các mẫu mã khác nhau để làm việc với tin nhắn có tệp đính kèm TNEF.

Đọc Tin Nhắn Khi Giữ Các Tệp Đính Kèm TNEF

Đoạn mã dưới đây cho bạn cách đọc một tin nhắn bằng cách giữ lại các tệp đính kèm TNEF.

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

EmlLoadOptions options = new EmlLoadOptions();

// This preserves the TNEF attachment as it is, if the file contains one
options.setPreserveTnefAttachments(true);

MailMessage eml = MailMessage.load(dataDir + "tnefEml.eml", options);

for (Attachment attachment : eml.getAttachments()) {
    System.out.println(attachment.getName());
}

Cập Nhật Tài Nguyên trong Tệp Đính Kèm TNEF và Giữ Định Dạng TNEF

Đoạn mã dưới đây cho bạn cách cập nhật tài nguyên trong tệp đính kèm TNEF và giữ nguyên định dạng TNEF.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
public static void updateTnefResources(String dataDir) throws Exception {
    String fileName = dataDir + "tnefEml.eml";
    String imgFileName = dataDir + "Untitled.jpg";
    String outFileName = dataDir + "01_SAVE_Preserve_out.eml";

    MailMessage originalMailMessage = MailMessage.load(fileName);
    updateResources(originalMailMessage, imgFileName);

    EmlSaveOptions emlSaveOptions = new EmlSaveOptions(MailMessageSaveType.getEmlFormat());
    emlSaveOptions.setFileCompatibilityMode(FileCompatibilityMode.PreserveTnefAttachments);

    originalMailMessage.save(outFileName, emlSaveOptions);
}

private static void updateResources(MailMessage msg, String imgFileName) throws Exception {
    for (int i = 0; i < msg.getAttachments().size(); i++) {
        Attachment attachment = msg.getAttachments().get_Item(i);
        String name = attachment.getContentType().getName();

        if (name.endsWith("jpg")) {
            attachment.setContentStream(new FileInputStream(imgFileName));
        } else if (name.endsWith("eml")) {
            // Replace the resources of the embedded message, then put it back
            ByteArrayOutputStream embedded = new ByteArrayOutputStream();
            attachment.save(embedded);

            MailMessage embeddedMessage = MailMessage.load(new ByteArrayInputStream(embedded.toByteArray()));
            updateResources(embeddedMessage, imgFileName);

            ByteArrayOutputStream processed = new ByteArrayOutputStream();
            embeddedMessage.save(processed, SaveOptions.getDefaultMsgUnicode());

            attachment.setContentStream(new ByteArrayInputStream(processed.toByteArray()));
        }
    }

    for (LinkedResource resource : msg.getLinkedResources()) {
        // Compare the media type with equals: == compares references, not the text
        if ("image/jpeg".equals(resource.getContentType().getMediaType())) {
            resource.setContentStream(new FileInputStream(imgFileName));
        }
    }
}

Thêm Tệp Đính Kèm Mới vào Tin Nhắn Chính chứa TNEF

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

String fileName = "MainMessage.eml";
String attachName = "barcode.png";
String outFileName = "test_out.eml";

MailMessage eml = MailMessage.load(dataDir + fileName);

try (FileInputStream fi = new FileInputStream(dataDir + attachName)) {
    eml.getAttachments().addItem(new Attachment(fi, attachName, "image/png"));
    eml.save(dataDir + outFileName);
}

Tạo TNEF EML từ MSG

Các tệp MSG của Outlook đôi khi chứa thông tin như bảng và kiểu văn bản có thể bị lỗi khi chuyển sang EML. Tạo tin nhắn TNEF từ các tệp MSG như vậy cho phép chúng ta giữ lại định dạng và thậm chí gửi các tin nhắn này qua các khách hàng email mà vẫn giữ định dạng.

// 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 + "Message.msg");

MailConversionOptions options = new MailConversionOptions();
options.setConvertAsTnef(true);

MailMessage mail = msg.toMailMessage(options);

Để tạo TNEF, có thể sử dụng đoạn mã mẫu dưới đây.

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

MsgLoadOptions msgLoadOptions = new MsgLoadOptions();

// The PreserveTnefAttachments option creates a TNEF EML out of an MSG file
msgLoadOptions.setPreserveTnefAttachments(true);

MailMessage eml = MailMessage.load(dataDir + "Message.msg", msgLoadOptions);

Phát Hiện Tin Nhắn Có Phải TNEF

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

MailMessage mail = MailMessage.load(dataDir + "test.eml");

boolean isTnef = mail.getOriginalIsTnef();
System.out.println("isTnef: " + isTnef);

Xử lý tin nhắn bị trả lại

Rất thường gặp khi một tin nhắn gửi đến người nhận có thể bị trả lại vì bất kỳ lý do nào, chẳng hạn như địa chỉ người nhận không hợp lệ. API Aspose.Email có khả năng xử lý tin nhắn như vậy để kiểm tra xem nó là email bị trả lại hay là tin nhắn email thông thường. The checkBounced phương thức của MailMessage lớp trả về kết quả hợp lệ nếu email là một email trả lại.

Bài viết này trình bày cách sử dụng BounceResult lớp, báo cáo một tin nhắn có phải là email trả lại và cung cấp thông tin chi tiết về người nhận, hành động đã thực hiện và lý do thông báo.

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

for (String fileName : new String[] { "failed.msg", "failed1.msg", "test.eml" }) {
    MailMessage mail = MailMessage.load(dataDir + fileName);
    BounceResult result = mail.checkBounced();

    System.out.println(fileName);
    System.out.println("IsBounced : " + result.isBounced());
    System.out.println("Action : " + result.getAction());
    System.out.println("Recipient : " + result.getRecipient());

    if (result.isBounced()) {
        System.out.println("Reason : " + result.getReason());
        System.out.println("Status : " + result.getStatus());
        System.out.println("OriginalMessage ToAddress 1: "
                + result.getOriginalMessage().getTo().get_Item(0).getAddress());
    }
    System.out.println();
}

Bỏ qua Ngoại lệ

Thư viện cung cấp một ExceptionManager lớp để ứng dụng của bạn có thể bỏ qua các ngoại lệ đã chọn, bỏ qua tất cả, hoặc ghi lại những ngoại lệ đã bỏ qua. Xem Cách bỏ qua ngoại lệ cho chi tiết và mẫu mã.

Bộ phân tích Spam Bayes

Aspose.Email cung cấp tiện ích lọc email bằng bộ phân tích spam Bayesian. Nó cung cấp SpamAnalyzer lớp cho mục đích này. Bài viết này chỉ cách huấn luyện bộ lọc để phân biệt spam và email thông thường bằng cơ sở dữ liệu từ.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
public static void spamFilterTest(String dataDir) {
    String hamFolder = dataDir + "ham";
    String spamFolder = dataDir + "spam";
    String testFolder = dataDir + "test";
    String databaseFile = dataDir + "SpamFilterDatabase.txt";

    teachAndCreateDatabase(hamFolder, spamFolder, databaseFile);

    SpamAnalyzer analyzer = new SpamAnalyzer(databaseFile);

    for (File testFile : new File(testFolder).listFiles()) {
        MailMessage msg = MailMessage.load(testFile.getAbsolutePath());
        System.out.println(msg.getSubject());
        printResult(analyzer.test(msg));
    }
}

private static void teachAndCreateDatabase(String hamFolder, String spamFolder, String databaseFile) {
    SpamAnalyzer analyzer = new SpamAnalyzer();

    // Train on the known-good messages, then on the known-spam ones
    train(analyzer, new File(hamFolder).listFiles(), false);
    train(analyzer, new File(spamFolder).listFiles(), true);

    analyzer.saveDatabase(databaseFile);
}

private static void train(SpamAnalyzer analyzer, File[] files, boolean isSpam) {
    for (File file : files) {
        try {
            analyzer.trainFilter(MailMessage.load(file.getAbsolutePath()), isSpam);
        } catch (RuntimeException e) {
            // Skip the files that cannot be loaded as messages
        }
    }
}

private static void printResult(double probability) {
    if (probability < 0.05) {
        System.out.println("This is ham");
    } else if (probability > 0.95) {
        System.out.println("This is spam");
    } else {
        System.out.println("Maybe spam");
    }
}

Lấy Preamble và Epilogue từ Tin nhắn EML

Trong định dạng MIME, preamble là văn bản xuất hiện sau các tiêu đề và trước ranh giới multipart đầu tiên. Epilogue là văn bản xuất hiện sau ranh giới cuối cùng và trước khi kết thúc tin nhắn. Văn bản này thường không hiển thị cho người dùng trong trình đọc mail, nhưng một số triển khai MIME dùng nó để chèn ghi chú cho người nhận đọc tin nhắn bằng chương trình không hỗ trợ MIME.

Phần mở đầu và phần kết được đọc và ghi bằng các phương thức tương ứng của MailMessage lớp:

String dataDir = "data/";

MailMessage eml = MailMessage.load(dataDir + "message.eml");

// Read the preamble and the epilogue of the loaded message
System.out.println("Preamble: " + eml.getPreamble());
System.out.println("Epilogue: " + eml.getEpilogue());

// Both can be set before saving the message again
eml.setPreamble("This is a multi-part message in MIME format.");
eml.setEpilogue("End of the MIME message.");

eml.save(dataDir + "message_out.eml", SaveOptions.getDefaultEml());

Hiển Thị Người Tham Dự Tùy Chọn trong Tệp MHT

Khi làm việc với định dạng MHT, bạn có thể hiển thị hoặc ẩn thông tin về người tham dự tùy chọn trong tiêu đề của các sự kiện lịch. Để cấu hình MhtSaveOptions đối với việc xử lý tệp MHT, bạn cần hiểu cách MhtFormatOptions.RenderCalendarEvent và MhtFormatOptions.WriteHeader các giá trị hoạt động:

  • MhtFormatOptions.RenderCalendarEvent - kiểm soát việc các chi tiết sự kiện lịch có được render trong tệp MHT hay không. Bằng cách bật tùy chọn này, bạn đảm bảo rằng thông tin sự kiện đầy đủ, bao gồm chi tiết người tham dự, được bao gồm trong đầu ra.
  • MhtFormatOptions.WriteHeader - xác định xem các tiêu đề chứa siêu dữ liệu như chủ đề, ngày, và thông tin người tham dự (bao gồm người tham dự tùy chọn, khi được cấu hình) có được ghi vào tệp MHT hay không.

Đoạn mã mẫu dưới đây minh hoạ cách sử dụng tính năng hiển thị người tham dự tùy chọn khi lưu tin nhắn ở định dạng MHTML:

MhtSaveOptions options = new MhtSaveOptions();
options.setMhtFormatOptions(MhtFormatOptions.RenderCalendarEvent | MhtFormatOptions.WriteHeader);

MailMessage eml = MailMessage.load("meeting.msg");
eml.save("meeting.mhtml", options);

Nếu bạn cần loại bỏ thông tin về người tham dự tùy chọn khỏi tệp MHT, hãy xóa mẫu định dạng cho người tham dự tùy chọn trước khi lưu:

MhtSaveOptions options = new MhtSaveOptions();
options.setMhtFormatOptions(MhtFormatOptions.RenderCalendarEvent | MhtFormatOptions.WriteHeader);

// Skip the optional attendees in the MHTML output
options.getFormatTemplates().set_Item(MhtTemplateName.OPTIONAL_ATTENDEES, "");

MailMessage eml = MailMessage.load("meeting.msg");
eml.save("meeting2.mhtml", options);

Lưu Tất Cả Tiêu Đề trong MHTML

Cái SaveAllHeaders thuộc tính của MhtSaveOptions lớp định nghĩa việc có nên ghi tất cả tiêu đề vào MHTML đầu ra hay không. Đoạn mã mẫu dưới đây cho bạn cách lưu tất cả tiêu đề của một tin nhắn vào tệp MHTML:

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

MhtSaveOptions sopt = SaveOptions.getDefaultMhtml();
sopt.setSaveAllHeaders(true);

eml.save("message.mhtml", sopt);

Theo Dõi Email bằng MDN và Biên Nhận Đọc

API Aspose.Email cung cấp hỗ trợ theo dõi email bằng Thông Báo Dòng Tình Trạng (MDN). Điều này đạt được bằng cách yêu cầu biên nhận đọc và tạo thông tin cần thiết:

  • MailMessage.setReadReceiptTo(MailAddressCollection) đặt địa chỉ biên nhận đọc.
  • MailMessage.createReadReceipt(String, String) xây dựng biên nhận đọc cho một tin nhắn đã nhận.
  • MapiMessage.setReadReceiptRequested(boolean) đặt việc yêu cầu biên nhận đọc cho một tin nhắn Outlook.

Đoạn mã dưới đây cho bạn thấy cách theo dõi email bằng API Aspose.Email:

try (SmtpClient client = new SmtpClient("smtp.server.com", 587, "username", "password")) {

    // Send a message with a requested read receipt
    MailMessage mailMessage = new MailMessage("from@domain.com", "to@domain.com",
            "test MDN", "This is a test message with read receipt requested");

    MailAddressCollection readReceiptTo = new MailAddressCollection();
    readReceiptTo.add("from@domain.com");
    readReceiptTo.add("another@domain.com");
    mailMessage.setReadReceiptTo(readReceiptTo);

    client.send(mailMessage);

    // On the recipient side: check the request, then create and send the read receipt
    MailMessage emlMDN = MailMessage.load("received.eml");
    if (emlMDN.getReadReceiptTo().size() > 0) {
        client.send(emlMDN.createReadReceipt("to@domain.com", null));
    }
}

Có thể yêu cầu biên nhận đọc trên một tin nhắn Outlook:

// Create a MapiMessage with a requested read receipt
MapiMessage mapiMessage = new MapiMessage("from@domain.com", "to@domain.com",
        "test MDN", "This is a read requested mapiMessage", OutlookMessageFormat.Unicode);
mapiMessage.setReadReceiptRequested(true);

// Or create a MailMessage with a requested read receipt and convert it to a MapiMessage
MailMessage mailMessage = new MailMessage("from@domain.com", "to@domain.com",
        "test MDN", "This is a test message with read receipt requested");

MailAddressCollection readReceiptTo = new MailAddressCollection();
readReceiptTo.add("from@domain.com");
mailMessage.setReadReceiptTo(readReceiptTo);

MapiMessage converted = MapiMessage.fromMailMessage(mailMessage, MapiConversionOptions.getUnicodeFormat());