Convert MHTML Files to Various Formats in Java
Converting MHTML files to various formats is a common requirement in many applications, especially those dealing with email archiving, document management, and data exchange. MHTML, or MIME HTML, is a web archive format used to combine HTML code and its resources, such as images, into a single file. However, for compatibility and usability purposes, it might be necessary to convert MHTML files into other formats such as MSG, EML, or OST. In this article, we will explore how to achieve this using Aspose.Email for Java.
Aspose.Email for Java simplifies the conversion process through its rich set of features and methods. The main components involved in the MHTML conversion process include:
- MhtmlLoadOptions: This class specifies the options for loading MHTML files. It allows for customization of how the MHTML content is interpreted and processed.
- MailMessage: This class represents an email message and serves as a bridge for loading MHTML content. It facilitates the extraction and manipulation of the email data within the MHTML file.
- SaveOptions: Depending on the target format, Aspose.Email for Java provides various save options such as EmlSaveOptions, MsgSaveOptions, etc. These options determine the parameters and settings for saving the converted file in the desired format.
Convert MHTML to EML
Converting MHTML to EML is one of the common tasks when dealing with email files. The EML format is widely used for storing individual email messages, making it a suitable format for email archiving and exchange. The code snippet below shows how Aspose.Email can be used to convert an MHTML file to EML format:
- Load the MHTML file using the MailMessage.load method.
- Save the loaded message as an EML file using the
savemethod of the MailMessage class. Specify the output file name and the save options.
// Load an existing MHTML file
MailMessage message = MailMessage.load("myMessage.mhtml");
message.save("output.eml", SaveOptions.getDefaultEml());
Convert MHTML to EMLX
The EMLX format is commonly used by Apple’s Mail application and is beneficial for users who need to ensure compatibility with macOS systems. The following code sample demonstrates the conversion:
- Load the MHTML file with the MailMessage.load method.
- Use the
savemethod of the MailMessage class to save the MHTML content as an EMLX file.
// Load the MHTML file to be converted
MailMessage message = MailMessage.load("My File.mhtml");
// Save the MHTML as an EMLX
message.save("Saved File.emlx", SaveOptions.createSaveOptions(MailMessageSaveType.getEmlxFormat()));
Convert MHTML to HTML
Converting MHTML files to HTML format is often necessary for displaying email content in web browsers or for further processing in web-based applications:
- Use the MailMessage.load method to load the MHTML file.
- Use the
savemethod of the MailMessage class to save the MHTML content as an HTML file.
// Load an existing MHTML file
MailMessage message = MailMessage.load("myMessage.mhtml");
message.save("output.html", SaveOptions.getDefaultHtml());
The library also allows modifying or adding custom properties to the HTML output, such as custom headers, subject, or body content. You can also embed resources within the HTML content if needed — see Convert EML to HTML for the available resource rendering modes.
Convert MHTML to ICS
Converting MHTML files to ICS format is essential for managing calendar events and appointments. Use the getAlternateViewContent method to extract the ICS content from the MHTML file. This method retrieves the calendar information in the “text/calendar” format:
- Load the MHTML file using the MailMessage.load method.
- Extract the ICS content with
getAlternateViewContent. - If the ICS content is not null, save it to a file.
MailMessage eml = MailMessage.load("message.mhtml", new MhtmlLoadOptions());
String icsView = eml.getAlternateViewContent("text/calendar");
if (icsView != null) {
Files.write(Paths.get("appointment.ics"), icsView.getBytes(StandardCharsets.UTF_8));
}
Customisation Options
Aspose.Email for Java provides several features that can be applied in the process of converting MHTML to ICS. These features offer enhanced control and flexibility, enabling developers to customize the conversion process according to specific requirements:
- Custom Date and Time Formats: You can specify custom date and time formats for the ICS content to match the desired output format.
- Timezone Handling: Manage timezone information to ensure that calendar events are accurately represented across different timezones.
- Encoding Options: Specify encoding options to ensure that the ICS content is correctly encoded, preventing issues with special characters.
- Handling Attachments: Extract and include attachments from the MHTML file in the ICS content, if necessary.
- Custom Properties: Add custom properties to the ICS file, such as custom fields or metadata.
Below is an example demonstrating how to create an Appointment object from the ICS content when converting MHTML to ICS:
// Load the MHTML file
MailMessage eml = MailMessage.load("message.mhtml", new MhtmlLoadOptions());
// Extract the ICS content
String icsView = eml.getAlternateViewContent("text/calendar");
if (icsView != null) {
// Create a new Appointment object from the ICS content
Appointment appointment = Appointment.load(
new ByteArrayInputStream(icsView.getBytes(StandardCharsets.UTF_8)));
// Customize the appointment properties
appointment.setStartDate(new GregorianCalendar(2024, java.util.Calendar.DECEMBER, 10).getTime());
appointment.setEndDate(new GregorianCalendar(2024, java.util.Calendar.DECEMBER, 11).getTime());
appointment.setSummary("Custom Event Summary");
// Save the customized ICS content to a file
appointment.save("custom_appointment.ics", AppointmentSaveFormat.Ics);
}
The customization, in this case, is achieved by utilizing the Appointment class, representing a calendar event, and its extensive methods and properties.
Convert MHTML to MBOX
The MBOX format is widely used for storing collections of email messages, and converting MHTML files to MBOX format can be particularly useful for archiving or migrating email data. Aspose.Email for Java provides the writeMessage method of the MboxrdStorageWriter class to write a message to the MBOX file:
- Load the MHTML file using MailMessage.load.
- Initialize the MboxrdStorageWriter to write the loaded message to an MBOX file.
- Write the message to the MBOX file.
try (MailMessage message = MailMessage.load("inputFile.mhtml", new MhtmlLoadOptions());
MboxrdStorageWriter writer = new MboxrdStorageWriter("output.mbox", new MboxSaveOptions())) {
writer.writeMessage(message);
}
Additional Options
- Custom Message Headers: Modify or add custom headers to the messages before saving them to the MBOX file.
- Handling Attachments: Ensure that attachments are correctly preserved and included in the converted MBOX file.
- Encoding Options: Specify encoding options to ensure that message content is correctly encoded, especially when dealing with special characters or different languages.
The code sample below demonstrates how to use some of these features when converting MHTML to MBOX:
// Load the MHTML file
try (MailMessage message = MailMessage.load("inputFile.mhtml", new MhtmlLoadOptions())) {
// Customize message headers
message.setSubject("Customized Subject");
message.getHeaders().add("X-Custom-Header", "CustomHeaderValue");
try (MboxrdStorageWriter writer = new MboxrdStorageWriter("output.mbox", new MboxSaveOptions())) {
// Write the message to the MBOX file
writer.writeMessage(message);
}
}
Convert MHTML to MSG
Converting MHTML files to MSG format is useful for scenarios where you need to manage or share email messages within Microsoft Outlook:
- Load the MHTML file using MailMessage.load.
- Use the
savemethod of the MailMessage class to save the loaded message as an MSG file, usingSaveOptions.getDefaultMsgUnicode()to make sure the file is saved with Unicode encoding.
MailMessage eml = MailMessage.load("message.mhtml", new MhtmlLoadOptions());
eml.save("message.msg", SaveOptions.getDefaultMsgUnicode());
Additional Features
Aspose.Email for Java offers several features that enhance control and customization options during the conversion:
- Custom Message Properties: Modify or add custom properties to the MSG file, such as custom headers, subject, or body content.
- Handling Attachments: Ensure that attachments are correctly preserved and included in the converted MSG file. You can also add new attachments or modify existing ones.
- Setting Message Flags: Set flags on the message, such as read/unread status or importance level.
- Encoding Options: Specify encoding options to ensure that message content is correctly encoded.
- HTML Formatting: Ensure that the HTML content of the email is correctly formatted and preserved in the MSG file.
The code sample below demonstrates how to use some of these features when converting MHTML to MSG:
// Load the MHTML file
MailMessage eml = MailMessage.load("message.mhtml", new MhtmlLoadOptions());
// Customize message properties
eml.setSubject("Customized Subject");
eml.getHeaders().add("X-Custom-Header", "CustomHeaderValue");
// Add an attachment
Attachment attachment = new Attachment("path/to/attachment.txt");
eml.getAttachments().addItem(attachment);
// Set the message priority
eml.setPriority(MailPriority.High);
// Save the loaded message as an MSG file with the default Unicode options
eml.save("message.msg", SaveOptions.getDefaultMsgUnicode());
Convert MHTML to OFT
Converting MHTML files to OFT format is useful for scenarios where you need to create email templates for Microsoft Outlook:
- Load the MHTML file using MailMessage.load.
- Save the loaded message as an OFT file using the
savemethod with theSaveOptions.getDefaultOft()save option.
MailMessage eml = MailMessage.load("message.mhtml", new MhtmlLoadOptions());
eml.save("message.oft", SaveOptions.getDefaultOft());
Special Features
Aspose.Email for Java offers several features that can be used in the process of converting MHTML to OFT, such as customizing message properties, handling attachments, setting message flags, encoding options, and HTML formatting. The code sample below modifies the subject, adds a custom header and a new attachment, assigns a high priority to the message, and only then saves it as a template:
MailMessage eml = MailMessage.load("message.mhtml", new MhtmlLoadOptions());
// Modify the subject and add a custom header
eml.setSubject("Customized Subject");
eml.getHeaders().add("X-Custom-Header", "CustomHeaderValue");
// Add a new attachment to the email message
Attachment attachment = new Attachment("path/to/attachment.txt");
eml.getAttachments().addItem(attachment);
// Assign a high priority to the message
eml.setPriority(MailPriority.High);
eml.save("message.oft", SaveOptions.getDefaultOft());
Convert MHTML to OST
If you need to store and manage email messages within Microsoft Outlook while offline, converting them to OST (Offline Storage Table) format might be useful:
- Use the PersonalStorage.fromFile method to load an existing OST file. Pass
trueas the second argument to open the storage for writing. - Use the MapiMessage.load method to load the MHTML file. This method reads the content of the MHTML file and converts it to a MapiMessage object.
- Locate the target folder within the OST file (e.g., “Inbox”) and use the
addMessagemethod to add the converted MHTML message to that folder.
try (PersonalStorage ost = PersonalStorage.fromFile("storage.ost", true)) {
// Load the MHTML file
MapiMessage msg = MapiMessage.load("message.mhtml", new MhtmlLoadOptions());
// Add the message to the OST file
FolderInfo folderInfo = ost.getRootFolder().getSubFolder("Inbox");
folderInfo.addMessage(msg);
}
Apart from the ability to modify or add custom properties to the message before saving it to the storage, Aspose.Email also allows adding new attachments or modifying existing ones, setting classification flags such as read/unread status or importance level, preserving the rich HTML formatting of the email content, and organizing messages into folders within the OST file:
// Load the OST file
try (PersonalStorage ost = PersonalStorage.fromFile("storage.ost", true)) {
// Load the MHTML file
MapiMessage msg = MapiMessage.load("message.mhtml", new MhtmlLoadOptions());
// Customize message properties
msg.setSubject("Customized Subject");
// Add an attachment
msg.getAttachments().add("attachment.txt", Files.readAllBytes(Paths.get("path/to/attachment.txt")));
// Mark the message as read
msg.setMessageFlags(MapiMessageFlags.MSGFLAG_READ);
// Set high importance
msg.setProperty(new MapiProperty(MapiPropertyTag.PR_IMPORTANCE, new byte[] { 2, 0, 0, 0 }));
// Get the target folder
FolderInfo folderInfo = ost.getRootFolder().getSubFolder("Inbox");
// Add the customized message to the OST file
folderInfo.addMessage(msg);
}
MapiMessage in Aspose.Email for Java has no setImportance method — the importance level is written directly as the PR_IMPORTANCE MAPI property, where 0 means low, 1 normal and 2 high.
Convert MHTML to PST
Converting MHTML files to PST (Personal Storage Table) format is useful for scenarios where you need to store and manage email messages within Microsoft Outlook:
- Create a new PST file with the PersonalStorage.create method. This method initializes a new PST file with the specified name and file format version.
- Create a subfolder within the PST file (e.g., “Inbox”) using the
addSubFoldermethod. - Load the MHTML file using the MapiMessage.load method.
- Add the message to the PST file with the
addMessagemethod.
try (PersonalStorage pst = PersonalStorage.create("outputFile.pst", FileFormatVersion.Unicode)) {
FolderInfo inbox = pst.getRootFolder().addSubFolder("Inbox");
MapiMessage msg = MapiMessage.load("sourceFile.mhtml", new MhtmlLoadOptions());
inbox.addMessage(msg);
}
For more options to be used while converting MHTML files to PST format, see Convert MHTML to OST.
Convert MHTML to VCF
Converting MHTML files to VCF (vCard) format is a common solution if you need to extract and save contact information from emails:
- Use the MailMessage.load method to load the MHTML file.
- Use the
getAlternateViewContentmethod to find the alternate view with the media type “text/vcard”. - Check if the vCard content is found, and if so, save it to a VCF file.
MailMessage eml = MailMessage.load("message.mhtml", new MhtmlLoadOptions());
String vcfView = eml.getAlternateViewContent("text/vcard");
if (vcfView != null) {
Files.write(Paths.get("contact.vcf"), vcfView.getBytes(StandardCharsets.UTF_8));
}
Special Features for MHTML to VCF Conversion
- Custom Property Handling: Modify or add custom properties to the vCard before saving it. This can include custom fields, additional contact information, or personalized data.
- Multi-Contact Extraction: Extract multiple contact entries if the MHTML file contains several vCard entries, and save each contact as a separate VCF file.
- Encoding Options: Ensure proper encoding of contact information to support various character sets and internationalization.
- vCard Versions: Convert and save the vCard in different versions (v2.1, v3.0, v4.0) based on the target application’s compatibility requirements.
- Handling Embedded Images: Extract and save embedded images or photos associated with the contacts in the vCard.
Below is an example demonstrating how to load the extracted vCard content into a VCardContact object and save it in a specific vCard version:
// Load the MHTML file
MailMessage eml = MailMessage.load("message.mhtml", new MhtmlLoadOptions());
// Find the alternate view with the "text/vcard" media type (VCF)
String vcfView = eml.getAlternateViewContent("text/vcard");
if (vcfView != null) {
// Load the extracted content into a VCardContact object
VCardContact contact = VCardContact.load(
new ByteArrayInputStream(vcfView.getBytes(StandardCharsets.UTF_8)));
// Save the contact using the required vCard version
VCardSaveOptions options = new VCardSaveOptions();
options.setVersion(VCardVersion.V30);
contact.save("contact.vcf", options);
}
See Working with vCard (VCF) Files for a detailed description of the vCard object model.