Loading and Saving Message

Loading and Saving Message

Detecting File Formats

Aspose.Email API provides the capability to detect the file format of the provided message file. The DetectFileFormat method of 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 detecting 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());

Loading a Message with Load Options

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

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

Saving and Converting 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 EML 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 EML 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 as 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());

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

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

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

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

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

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

Saving Message as HTML

The HtmlSaveOptions class allows you to export the message body to HTML. The following code snippet shows you how to Save 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);

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