Utility Features - MailMessage

Encrypting and Decrypting Messages

Aspose.Email provides facility to Encrypt and decrypt Email messages. This topic shows how an existing or new message can be loaded and encrypted using MailMessage. The encrypt() and decrypt() methods return the MailMessage object for the applied effects and needs to be taken care of while encrypting/decrypting messages. Encrypting and decrypting messages involves the following steps:

  1. Create a new message or load an existing one
  2. Encrypt the message using the certificate file
  3. Send the message or save it
  4. Decrypt the message as required

The following code snippet shows you how to encrypt and decrypt messages.

// 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();
}

Checking a Message for Encryption

Aspose.Email MailMessage class allows checking a message if it is encrypted or not. The isEncrypted property of MailMessage allows checking this as shown in the following code sample.

// 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();
}

Signing and Encrypting Messages with S/MIME Keys

Aspose.Email for Java represents a certificate, with or without its private key, as an SmimeKey. There is no X509Certificate2 type in the Java API: a key is loaded from a PFX, a private key file or a certificate file with the static factory methods of SmimeKey, and that object is then passed to the signing and encryption methods of 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());
}

Configure Locale Options for Aspose.Email

You can use the LocaleOptions class when the default locale is not recognised, and set the most appropriate locale for the Aspose.Email library. It offers the following methods:

The following code sample demonstrates how to load a mail message from a file using the specified locale settings:

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");

This code ensures that the application and the Aspose.Email library use the specified locales for handling language, country, and cultural conventions.

MailMessages Containing TNEF attachments

Transport Neutral Encapsulation Format (TNEF) is a proprietary email attachment format used by Microsoft Outlook and Microsoft Exchange Server. The Aspose.Email API allows you to read email messages that have TNEF attachments and modify the contents of them. The email can then be saved as a normal email or to the same format, preserving TNEF attachments. This article shows different code samples for working with messages containing TNEF attachments.

Reading a Message by Preserving TNEF Attachments

The following code snippet shows you how to read a message by preserving TNEF attachments.

// 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());
}

Updating Resources in a TNEF Attachment and Preserving TNEF Format

The following code snippet shows you how to update resources in a TNEF attachment and preserve the TNEF format.

// 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));
        }
    }
}

Adding New Attachments to Main Message Containing 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);
}

Creating TNEF EML from MSG

Outlook MSGs sometimes contain information such as tables and text styles that may get disturbed if these are converted to EML. Creating TNEF messages from such MSG files allows us to retain the formatting and even send such messages via the email clients retaining the formatting.

// 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);

To create the TNEF, the following sample code can be used.

// 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);

Detect if a Message is 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);

Processing Bounced Messages

It is very common that a message sent to a recipient may bounce for any reason such as an invalid recipient address. Aspose.Email API has the capability to process such a message for checking if it is a bounced email or a regular email message. The checkBounced method of the MailMessage class returns a valid result if the email message is a bounced email.

This article shows the usage of the BounceResult class, which reports whether a message is a bounced email and gives detailed information about the recipients, the action taken and the reason for the notification.

// 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();
}

Ignore Exceptions

The library offers an ExceptionManager class so that your application can ignore selected exceptions, ignore all of them, or log the ones it ignores. See How to Ignore Exceptions for the details and code samples.

Bayesian Spam Analyzer

Aspose.Email provides the facility of email filtering using a Bayesian spam analyzer. It provides the SpamAnalyzer class for this purpose. This article shows how to train the filter to distinguish spam from regular emails using a word database.

// 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");
    }
}

Obtaining Preamble and Epilogue from EML Messages

In the MIME format, the preamble is the text that appears after the headers and before the first multipart boundary. The epilogue is the text that appears after the last boundary and before the end of the message. This text is usually not visible to users in mail readers, but some MIME implementations use it to insert notes for recipients who read the message with non-MIME-compliant programs.

The preamble and the epilogue are read and written with the corresponding methods of the MailMessage class:

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());

Display Optional Attendees in MHT Files

When working with the MHT format, you can display or hide information about optional attendees in the header of calendar events. To configure MhtSaveOptions for MHT file handling, you need to understand how the MhtFormatOptions.RenderCalendarEvent and MhtFormatOptions.WriteHeader values work:

  • MhtFormatOptions.RenderCalendarEvent - controls whether details of calendar events are rendered in the MHT file. By setting this option, you ensure that comprehensive event information, including attendee details, is included in the output.
  • MhtFormatOptions.WriteHeader - determines if headers containing metadata such as subject, date, and participant information (including optional attendees, when configured) are written into the MHT file.

The code sample below demonstrates how to use the display optional attendees feature when saving a message in MHTML format:

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

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

If you need to exclude information about optional attendees from the MHT file, clear the format template for the optional attendees before saving:

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);

Save All Headers in MHTML

The SaveAllHeaders property of the MhtSaveOptions class defines whether all headers should be written to the output MHTML or not. The following code snippet shows you how to save all headers of a message into an MHTML file:

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

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

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

Email Tracking using MDN and Read Receipts

Aspose.Email API provides support for email tracking using Message Disposition Notification (MDN). This is achieved by requesting read receipts and creating the required information:

  • MailMessage.setReadReceiptTo(MailAddressCollection) sets the read receipt addresses.
  • MailMessage.createReadReceipt(String, String) builds a read receipt for a received message.
  • MapiMessage.setReadReceiptRequested(boolean) sets whether a read receipt is requested for an Outlook message.

The following code snippet shows you how to track email using the Aspose.Email API:

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));
    }
}

A read receipt can also be requested on an Outlook message:

// 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());