Loading and Saving Messages

Loading and Saving Email Messages

Detect a File Format

Aspose.Email API provides the capability to detect the file format of the provided message file. The DetectFileFormat method of the FileFormatUtil class can be used to achieve this. The following classes and methods can be used to detect the loaded file format.

The following code snippet shows you how to detect file formats.

// 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 = Utils.getSharedDataDir(DetectingFileFormat.class) + "email/";
//Detect file format
FileFormatInfo info = FileFormatUtil.detectFileFormat(dataDir + "Message.msg");
//Gets the detected load format
System.out.println("The message format is: " + info.getFileFormatType());

Load an Email Message

To load a message with specific load options, Aspose.Email provides the LoadOptions class that can be used as follow:

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Loading with default options
// Load from eml
MailMessage eml = MailMessage.load("test.eml", new EmlLoadOptions());
// Load from html
MailMessage html = MailMessage.load("test.html", new HtmlLoadOptions());
// load from mhtml
MailMessage mhtml = MailMessage.load("test.mhtml", new MhtmlLoadOptions());
// load from msg
MailMessage msg = MailMessage.load("test.msg", new MsgLoadOptions());
// load from thef fomat
MailMessage thef = MailMessage.load("winmail.dat", new TnefLoadOptions());
// Loading with custom options
EmlLoadOptions opt = new EmlLoadOptions();
opt.setPreserveTnefAttachments(true);
MailMessage emlMailMessage = MailMessage.load("test.html", opt);
HtmlLoadOptions htmlOpt = new HtmlLoadOptions();
htmlOpt.shouldAddPlainTextView(true);
MailMessage htmlMailMessage = MailMessage.load("test.html", htmlOpt);

Preserve Embedded Message Format during Loading

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = Utils.getSharedDataDir(DisplayEmailInformation.class) + "email/";
EmlLoadOptions options = new EmlLoadOptions();
options.setPreserveEmbeddedMessageFormat(true);
MailMessage mail = MailMessage.load(dataDir + "tnefWithMsgInside.eml", options);
int fileFormat = FileFormatUtil.detectFileFormat(mail.getAttachments().get_Item(0).getContentStream()).getFileFormatType();
System.out.println("Embedded message file format: " + fileFormat);

Save and Convert Email Messages

Aspose.Email makes it easy to convert any message type to another format. To demonstrate this feature, the code in this article loads three types of messages from disk and saves them back in other formats. The base class SaveOptions and the classes EmlSaveOptions, MsgSaveOptions, MhtSaveOptions, HtmlSaveOptions for additional settings when saving MailMessage can be used for saving messages to other formats. The article shows how to use these classes to save a sample email as:

  • EML format.
  • Outlook MSG.
  • MHTML format.
  • HTML format.

Load and Save an Email Message

The following code snippet shows you how to load an EML message and saves it to the disc in the same format.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MailMessage msg = MailMessage.load(dataDir + "test.eml", new EmlLoadOptions());
// Save the Email message to disk by using the SaveOptions
msg.save(dataDir + "LoadAndSaveFileAsEML_out.eml", SaveOptions.getDefaultEml());

Load and Save an Email Message Preserving the Original Boundaries

The following code snippet shows you how to load EML and save as EML preserving the original boundaries.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MailMessage eml = MailMessage.load(dataDir + "test.eml");
// Save as eml with preserved original boundares
EmlSaveOptions emlSaveOptions = new EmlSaveOptions(MailMessageSaveType.getEmlFormat());
emlSaveOptions.setPreserveOriginalBoundaries(true);
eml.save(dataDir + "PreserveOriginalBoundaries_out.eml", emlSaveOptions);

Saving as EML Preserving TNEF Attachments

The following code snippet shows you how to save as EML preserving TNEF attachments.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MailMessage eml = MailMessage.load(dataDir + "PreserveOriginalBoundaries.eml");
// Save as eml with preserved thef attachment
EmlSaveOptions emlSaveOptions = new EmlSaveOptions(MailMessageSaveType.getEmlFormat());
emlSaveOptions.setFileCompatibilityMode(FileCompatibilityMode.PreserveTnefAttachments);
eml.save(dataDir + "PreserveTNEFAttachment_out.eml", emlSaveOptions);

Save EML to MSG

The following code snippet shows you how to loads an EML message and converts it to MSG using the appropriate option from SaveOptions.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Initialize and Load an existing EML file by specifying the MessageFormat
MailMessage eml = MailMessage.load(dataDir + "test.eml");
//Save the Email message to disk in Unicode format
eml.save(dataDir + "LoadingEMLSavingToMSG_out.msg", SaveOptions.getDefaultMsgUnicode());

Save EML to MSG with Preserved Dates

The MsgSaveOptions class allows you to save the source message as an Outlook Message file (MSG) preserving dates. The following code snippet shows you how to Saving as MSG with Preserved Dates.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MailMessage eml = MailMessage.load(dataDir + "test.eml");
// Save as msg with preserved dates
MsgSaveOptions msgSaveOptions = new MsgSaveOptions(MailMessageSaveType.getOutlookMessageFormatUnicode());
msgSaveOptions.setPreserveOriginalDates(true);
eml.save(dataDir + "SavingAsMSGWithPreservedDates_out.msg", msgSaveOptions);

Save EML as MHTML

Different options of MHTML can be used to obtain the desired results. The following code snippet shows you how to load an EML message into MailMessage and convert it to MHTML with a message date in the UTC system.

// Set options for MHTML output
MhtSaveOptions saveOptions = SaveOptions.getDefaultMhtml();
// save a message date as UTC date
saveOptions.setPreserveOriginalDate(false);

// Initialize and load an existing EML file
try (MailMessage mailMessage = MailMessage.load(dataDir + "Message.eml")) {
    mailMessage.save(outDir + "Message_out.mhtml", saveOptions);
}

Format MHT Headers Globally when Saving from EML

With Aspose.Email, you can use the global formatting options for the Mht header. The global options set the common formatting of an Mht header for all MhtSaveOptions instances. This feature is designed to avoid setting formatting for each instance of MhtSaveOptions.

Use the following methods of the GlobalFormattingOptions class and the code sample below to set the formatting of an Mht header:

// saveOptions1 and saveOptions2 have the same mht header formatting
MhtSaveOptions saveOptions1 = new MhtSaveOptions();
MhtSaveOptions saveOptions2 = new MhtSaveOptions();

Convert EML to MHTML with Optional Settings

The MhtSaveOptions class provides additional options for saving email messages to MHTML format. The enumerator MhtFormatOptions makes it possible to write additional email information to the output MHTML. The following additional fields can be written:

  • WriteHeader - write the email header to the output file.
  • WriteOutlineAttachments - write outline attachments to the output file.
  • WriteCompleteEmailAddress - write the complete email address to the output file.
  • NoEncodeCharacters - no transfer encoding of characters should be used.
  • HideExtraPrintHeader - hide extra print header from the top of the output file.
  • WriteCompleteToEmailAddress - write the complete recipient email address to the output file.
  • WriteCompleteFromEmailAddress - write the complete sender email address to the output file.
  • WriteCompleteCcEmailAddress - write the complete email addresses of any carbon-copied recipients to the output file.
  • WriteCompleteBccEmailAddress - write the complete email address of any blind carbon-copied recipients to the output file.
  • RenderCalendarEvent - write text from the calendar event to the output file.
  • SkipByteOrderMarkInBody - write Byte Order Mark(BOM) bytes to the output file.
  • RenderVCardInfo -write text from VCard AlternativeView to the output file.
  • DisplayAsOutlook - display From header.
  • RenderTaskFields - writes specific Task fields to the output file.
  • None - No setting specified.

The following code snippet shows you how to convert EML files to MHTML with optional settings.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MailMessage eml = MailMessage.load(dataDir + "test.eml");
// Save as Mht with header
MhtSaveOptions mhtSaveOptions = new MhtSaveOptions();
int iSaveOptions = MhtFormatOptions.WriteHeader | MhtFormatOptions.HideExtraPrintHeader;
mhtSaveOptions.setMhtFormatOptions(iSaveOptions);
eml.save(dataDir + "ConvertingToMHTMLWithOptionalSettings_out.mht", mhtSaveOptions);

Render Calendar Events while Converting to MHTML

The MhtFormatOptions.RenderCalendarEvent renders the Calendar events to the output MTHML.The following code snippet shows you how to render calendar events while converting to MHTML.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = Utils.getSharedDataDir(RenderingCalendarEvents.class) + "email/";
MailMessage msg = MailMessage.load(dataDir + "Meeting with Recurring Occurrences.msg");
MhtSaveOptions options = new MhtSaveOptions();
{
options.setMhtFormatOptions(MhtFormatOptions.WriteHeader | MhtFormatOptions.RenderCalendarEvent);
//Format the output details if required - optional
//Set the display for Start Property
if (options.getFormatTemplates().containsKey(MhtTemplateName.START))
options.getFormatTemplates().set_Item(MhtTemplateName.START,"<span class='headerLineTitle'>Start:</span><span class='headerLineText'>{0}</span><br/>");
else
options.getFormatTemplates().add(MhtTemplateName.START, "<span class='headerLineTitle'>Start:</span><span class='headerLineText'>{0}</span><br/>");
//Set the display for End Property
if (options.getFormatTemplates().containsKey(MhtTemplateName.END))
options.getFormatTemplates().set_Item(MhtTemplateName.END, "<span class='headerLineTitle'>End:</span><span class='headerLineText'>{0}</span><br/>");
else
options.getFormatTemplates().add(MhtTemplateName.END, "<span class='headerLineTitle'>End:</span><span class='headerLineText'>{0}</span><br/>");
//Set the display for Recurrence Property
if (options.getFormatTemplates().containsKey(MhtTemplateName.RECURRENCE))
options.getFormatTemplates().set_Item(MhtTemplateName.RECURRENCE,"<span class='headerLineTitle'>Recurrence:</span><span class='headerLineText'>{0}</span><br/>");
else
options.getFormatTemplates().add(MhtTemplateName.RECURRENCE, "<span class='headerLineTitle'>Recurrence:</span><span class='headerLineText'>{0}</span><br/>");
//Set the display for RecurrencePattern Property
if (options.getFormatTemplates().containsKey(MhtTemplateName.RECURRENCE_PATTERN))
options.getFormatTemplates().set_Item(MhtTemplateName.RECURRENCE_PATTERN, "<span class='headerLineTitle'>RecurrencePattern:</span><span class='headerLineText'>{0}</span><br/>");
else
options.getFormatTemplates().add(MhtTemplateName.RECURRENCE_PATTERN, "<span class='headerLineTitle'>RecurrencePattern:</span><span class='headerLineText'>{0}</span><br/>");
//Set the display for Organizer Property
if (options.getFormatTemplates().containsKey(MhtTemplateName.ORGANIZER))
options.getFormatTemplates().set_Item(MhtTemplateName.ORGANIZER, "<span class='headerLineTitle'>Organizer:</span><span class='headerLineText'>{0}</span><br/>");
else
options.getFormatTemplates().add(MhtTemplateName.ORGANIZER, "<span class='headerLineTitle'>Organizer:</span><span class='headerLineText'>{0}</span><br/>");
//Set the display for RequiredAttendees Property
if (options.getFormatTemplates().containsKey(MhtTemplateName.REQUIRED_ATTENDEES))
options.getFormatTemplates().set_Item(MhtTemplateName.REQUIRED_ATTENDEES, "<span class='headerLineTitle'>RequiredAttendees:</span><span class='headerLineText'>{0}</span><br/>");
else
options.getFormatTemplates().add(MhtTemplateName.REQUIRED_ATTENDEES, "<span class='headerLineTitle'>RequiredAttendees:</span><span class='headerLineText'>{0}</span><br/>");
};
msg.save(dataDir + "Meeting with Recurring Occurrences_out.mhtml", options);

Export Email to MHT without Inline Images

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MailMessage eml = MailMessage.load(dataDir + "Message.msg", new MsgLoadOptions());
MhtSaveOptions mhtSaveOptions = new MhtSaveOptions();
mhtSaveOptions.setSkipInlineImages(true);
eml.save(dataDir + "EmlToMhtmlWithoutInlineImages_out.mht", mhtSaveOptions);

Export Email to MHT with Customized TimeZone

MailMessage class provides the setTimeZoneOffset property to set customized Timezone while exporting to MHT. The following code snippet shows you how to export email to MHT with customized TimeZone.

MailMessage msg = MailMessage.load(filename, new MsgLoadOptions());
msg.setDate(new Date());

// Set the timezone offset in milliseconds
msg.setTimeZoneOffset(5*60*60*1000);

MhtSaveOptions mhtOptions = new MhtSaveOptions();
mhtOptions.setMhtFormatOptions(MhtFormatOptions.WriteHeader);
msg.save(dataDir + "ExportToMHTWithCustomTimezone_out.mhtml", mhtOptions);

Exporting Email to EML

The following code snippet shows you how to export emails to EML.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
eml.save(dataDir + "testEml_out.eml", SaveOptions.getDefaultEml());

Save Email as HTML

The HtmlSaveOptions class allows you to export the message body to HTML. The following code snippet shows you how to save a message as HTML.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MailMessage msg = MailMessage.load(dataDir + "Message.msg");
msg.save(dataDir + "SavingMessageAsHTML_out1.html", SaveOptions.getDefaultHtml());
//or
MailMessage eml = MailMessage.load(dataDir + "test.eml");
HtmlSaveOptions options = SaveOptions.getDefaultHtml();
options.setEmbedResources(false);
options.setHtmlFormatOptions(HtmlFormatOptions.WriteHeader | HtmlFormatOptions.WriteCompleteEmailAddress);
eml.save(dataDir + "SavingMessageAsHTML_out2.html", options);

Save Email Message as HTML with Relative Path to Resources

When exporting email messages to HTML format, it is possible to choose to save email resources with relative paths. This feature provides more flexibility in how resources are linked in the output HTML file, making it easier to share and display saved emails on different systems. The HtmlSaveOptions.UseRelativePathToResources property provides ability to save resources with relative paths. Default property value is false (resources are saved with absolute paths). When set to true, resources are saved with relative paths. HTML files with relative paths are more portable and can be viewed correctly regardless of the hosting environment file structure. You can choose between absolute and relative paths depending on the requirements. You can define custom paths for resources using the ResourceHtmlRenderingHandler event.

Save with Default Relative Path to Resources

MapiMessage msg = MapiMessage.load(sourceFileName);

HtmlSaveOptions htmlSaveOptions = new HtmlSaveOptions();
htmlSaveOptions.setResourceRenderingMode(ResourceRenderingMode.SaveToFile);
htmlSaveOptions.setUseRelativePathToResources(true);

msg.save("target.html", htmlSaveOptions);

In this case, resources will be saved in the [html file name].files folder, in the same path as the .html file and the HTML will reference the resources via relative paths.

Save with Absolute Path to Resources

MapiMessage msg = MapiMessage.load(sourceFileName);

HtmlSaveOptions htmlSaveOptions = new HtmlSaveOptions();
htmlSaveOptions.setResourceRenderingMode(ResourceRenderingMode.SaveToFile);
htmlSaveOptions.setUseRelativePathToResources(false);

msg.save("target.html", htmlSaveOptions);

As in the first case, resources will be saved in the [html file name].files folder by default, but the HTML will reference resources using absolute paths.

Custom Relative Path using ResourceHtmlRenderingHandler Event

MapiMessage msg = MapiMessage.load(sourceFileName);

HtmlSaveOptions htmlSaveOptions = new HtmlSaveOptions();
htmlSaveOptions.setResourceRenderingMode(ResourceRenderingMode.SaveToFile);
htmlSaveOptions.setUseRelativePathToResources(false);

htmlSaveOptions.setResourceHtmlRenderingHandler(new ResourceHtmlRenderingHandler() {
    @Override
    public void invoke(Object sender, ResourceHtmlRenderingEventArgs args) {
        if (sender instanceof AttachmentBase) {
            AttachmentBase attachment = (AttachmentBase) sender;
            // Since UseRelativePathToResources = true, you should assign a relative path to the PathToResourceFile property.
            args.setPathToResourceFile("images\\" + attachment.getContentType().getName());
        }
    }
});

msg.save(targetPath + "A Day in the Park.html", htmlSaveOptions);

By using the ResourceHtmlRenderingHandler event, you can set custom relative or absolute paths for resources. When customizing paths with the ResourceHtmlRenderingHandler event handler, and since UseRelativePathToResources is set to true, you should assign a relative path to the PathToResourceFile property to ensure correct referencing.

Preserve Custom Icons in a Message while Converting to HTML

Sometimes, the message contains in-line attachments, that are displayed as icon images in a message body. Such messages may create problems while converting them to HTML, since the icon images are lost. This is because attachment’s icons are not held directly in the message.

The user of the Aspose.Email can customize the icons for attachments when converting the message to HTML. For that, the HtmlSaveOptions.ResourceHtmlRendering event is used to customize the rendering of resource files (such as attachments) when saving an email message as an HTML file. In the code sample below, the event handler is used to dynamically set the path to resource files (icons) based on the content type of the attachment. This allows for customized rendering of resources in the HTML output based on their file type.


 HtmlSaveOptions options = new HtmlSaveOptions();

options.setResourceHtmlRenderingHandler(new ResourceHtmlRenderingHandler() {

   @Override

   public void invoke(Object sender, ResourceHtmlRenderingEventArgs e) {

        AttachmentBase attachment = (AttachmentBase) sender;

        e.setCaption(attachment.getContentType().getName());

       if (attachment.getContentType().getName().endsWith(".pdf")) {

            e.setPathToResourceFile("pdf_icon.png");

       } else if (attachment.getContentType().getName().endsWith(".docx")) {

            e.setPathToResourceFile("word_icon.jpg");

       } else if (attachment.getContentType().getName().endsWith(".jpg")) {

            e.setPathToResourceFile("jpeg_icon.png");

       } else {

            e.setPathToResourceFile("not_found_icon.png");

       }

   }

});

options.setResourceRenderingMode(ResourceRenderingMode.SubstituteFromFile);

String fileName = "message.msg";

MailMessage mailMessage = MailMessage.load(fileName);

mailMessage.save("fileName.html", options);

Set Time and Timezone when Saving EML as HTML

Aspose.Email users can set the time and timezone display formats in HtmlSaveOptions. The HeadersFormattingOptions class allows to specify headers formatting options when saving MailMessage to Mhtml or Html format. The following methods of the HtmlFormatOptions class specify the fields to be displayed in the output file:

  • RenderCalendarEvent - Indicates that text from calendar event should be written in output mhtml.
  • RenderVCardInfo - Indicates that text from VCard AlternativeView should be written in output html.

The following code sample shows how to set the time and timezone when saving EML to HTML:

MailMessage msg = MailMessage.load("fileName");
HtmlSaveOptions options = new HtmlSaveOptions();
options.setHtmlFormatOptions(HtmlFormatOptions.WriteHeader);
options.getFormatTemplates().set_Item("DateTime", "MM d yyyy HH:mm tt");

Saving as HTML without Embedding Resources

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String fileName = dataDir + "EmailWithAttandEmbedded.eml";
MailMessage eml = MailMessage.load(fileName);
//final String outDir = "out path";
String outFileName = "EmailWithAttandEmbedded_out.html";
HtmlSaveOptions options = new HtmlSaveOptions();
options.setEmbedResources(false);
options.setSaveResourceHandler(new SaveResourceHandler() {
@Override
public void invoke(AttachmentBase attachment, String[] resourcePath) {
String dataDir = Utils.getSharedDataDir(ConvertEmailMessages.class) + "email/";
attachment.save(dataDir + attachment.getContentId());
resourcePath[0] = dataDir + attachment.getContentId();
}
});
eml.save(dataDir + outFileName, options);

Saving a Message as an Outlook Template (.oft) file

The following code snippet shows you how to save a message as an outlook template (.oft) file.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MailMessage eml = new MailMessage("test@from.to", "test@to.to", "template subject", "Template body");
String oftEmlFileName = "EmlAsOft_out.oft";
MsgSaveOptions options = SaveOptions.getDefaultMsgUnicode();
options.setSaveAsTemplate(true);
eml.save(dataDir + oftEmlFileName, options);