메시지 로드 및 저장

이메일 메시지 로드 및 저장

파일 형식 감지

Aspose.Email API는 제공된 메시지 파일의 파일 형식을 감지하는 기능을 제공합니다. The DetectFileFormat 메서드 FileFormatUtil 이 작업을 수행할 수 있는 클래스입니다. 다음 클래스와 메서드를 사용하여 로드된 파일 형식을 감지할 수 있습니다.

다음 코드 스니펫은 파일 형식을 감지하는 방법을 보여줍니다.

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

// Detect the file format
FileFormatInfo info = FileFormatUtil.detectFileFormat(dataDir + "Message.msg");

// Get the detected load format
System.out.println("The message format is: " + info.getFileFormatType());

RFC 메시지 파일 감지

메일 서버와 아카이빙 도구는 종종 MIME 콘텐츠를 포함하지만 표준 EML 또는 MHT 파일이 아닌 형태로 파일에 저장합니다. 예를 들어 .trn 확장자. 이러한 파일은 RFC 메시지로 식별됩니다: detectFileFormat 반환합니다 FileFormatType.RfcMessage 이를 위한 값입니다. 이렇게 하면 파일을 이메일 메시지로 인식하고 알 수 없는 형식으로 건너뛰지 않고 처리할 수 있습니다.

FileFormatInfo info = FileFormatUtil.detectFileFormat("message.trn");

if (info.getFileFormatType() == FileFormatType.RfcMessage) {
    // The file contains MIME content, so it can be loaded as an email message
    MailMessage message = MailMessage.load("message.trn");
    System.out.println("Body: " + message.getBody());
}

이메일 메시지 로드

특정 로드 옵션으로 메시지를 로드하려면 Aspose.Email가 제공합니다. LoadOptions 다음과 같이 사용할 수 있는 클래스:

// 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 the TNEF format
MailMessage tnef = MailMessage.load("winmail.dat", new TnefLoadOptions());

// Loading with custom options
EmlLoadOptions emlOptions = new EmlLoadOptions();
emlOptions.setPreserveTnefAttachments(true);
MailMessage emlMailMessage = MailMessage.load("test.eml", emlOptions);

HtmlLoadOptions htmlOptions = new HtmlLoadOptions();
htmlOptions.shouldAddPlainTextView(true);
MailMessage htmlMailMessage = MailMessage.load("test.html", htmlOptions);

EML에서 로드

이 섹션에서는 다음을 사용하여 EML 파일을 MailMessage 객체로 로드하는 방법을 설명합니다: EmlLoadOptions 클래스. 이 클래스는 포함된 메시지 형식을 보존하거나 TNEF 첨부 파일 로드 동작을 제어하는 등 EML 파일 로드 방식을 사용자 정의할 수 있는 옵션을 제공합니다.

  1. EmlLoadOptions 인스턴스를 초기화합니다.
  2. 필요에 따라 로드 옵션을 구성합니다.
  3. 다음 사용 MailMessage.load() 지정된 옵션으로 EML 파일을 로드하는 메서드.
// Initialize EmlLoadOptions
EmlLoadOptions loadOptions = new EmlLoadOptions();

// Configure the load options
loadOptions.setPreferredTextEncoding(StandardCharsets.UTF_8);  // preferred encoding for the message
loadOptions.setPreserveEmbeddedMessageFormat(true);            // preserve the format of embedded messages
loadOptions.setPreserveTnefAttachments(true);                  // control TNEF attachment loading
loadOptions.setRemoveSignature(false);                         // do not remove the signature

// Load the EML file
MailMessage eml = MailMessage.load("file.eml", loadOptions);

EmlLoadOptions 속성

  • PreferredTextEncoding - 메시지 제목과 본문의 선호 인코딩을 설정합니다. 기본값은 null.
  • PreserveEmbeddedMessageFormat - 로드 중에 포함된 메시지의 형식을 보존할지 여부를 나타냅니다. 기본값은 false.
  • PreserveTnefAttachments - TNEF 첨부 로딩 동작을 제어합니다. 기본값은 false.
  • RemoveSignature - 로드 중에 서명을 제거할지 여부를 지정합니다. 기본값은 false.

서명 포함/제외 메시지 로드

EML 파일을 로드할 때 기본적으로 서명 보존이 지원됩니다. 서명을 제거하려면 설정하십시오. setRemoveSignature(true):

EmlLoadOptions loadOptions = new EmlLoadOptions();
loadOptions.setRemoveSignature(true);

MailMessage msg = MailMessage.load("signed.eml", loadOptions);

EMLX에서 로드

다음은 EmlxLoadOptions 클래스는 EmlLoadOptions와 유사한 옵션을 제공하며, 인코딩, 서명 제거 및 포함된 메시지 형식에 대한 제어를 제공합니다.

// Instantiate EmlxLoadOptions
EmlxLoadOptions loadOptions = new EmlxLoadOptions();

loadOptions.setPreferredTextEncoding(StandardCharsets.UTF_8);
loadOptions.setPreserveEmbeddedMessageFormat(true);
loadOptions.setRemoveSignature(true);

// Load the EMLX file
MailMessage emlx = MailMessage.load("file.emlx", loadOptions);

EmlxLoadOptions 속성

  • PreferredTextEncoding - 메시지 제목과 본문의 선호 인코딩을 설정합니다. 기본값은 null.
  • PreserveEmbeddedMessageFormat - 임베디드 메시지 형식을 보존할지 여부를 나타냅니다. 기본값은 false.
  • RemoveSignature - 로드 중 서명을 제거할지 여부를 지정합니다. 기본값은 false.

HTML에서 로드

다음은 HtmlLoadOptions 클래스는 HTML 콘텐츠를 처리하도록 특별히 설계되었으며, 리소스 관리 및 평문 텍스트 보기 추가 옵션을 제공합니다.

// Initialize HtmlLoadOptions
HtmlLoadOptions loadOptions = new HtmlLoadOptions();

loadOptions.setPathToResources("resources/");                 // directory containing the resource files
loadOptions.setPreferredTextEncoding(StandardCharsets.UTF_8);
loadOptions.shouldAddPlainTextView(true);                     // add a plain text view of the body

// Load the HTML file
MailMessage html = MailMessage.load("file.html", loadOptions);

HtmlLoadOptions 속성

  • PathToResources - 리소스 파일(예: 이미지)이 포함된 디렉터리 경로를 정의합니다.
  • PreferredTextEncoding - 메시지 제목과 본문의 선호 인코딩을 설정합니다. 기본값은 null.
  • PreserveEmbeddedMessageFormat - 임베디드 메시지 형식 보존 여부를 결정합니다. 기본값은 false.
  • shouldAddPlainTextView(boolean) - 메시지 본문의 평문 텍스트 보기를 추가할지 여부를 지정합니다. 기본값은 false. 접근자 이름에 유의하십시오: 이는 setShouldAddPlainTextView.

MHTML에서 로드

다음은 MhtmlLoadOptions 클래스는 인코딩 관리, 임베디드 메시지 형식 보존 및 TNEF 첨부 처리 옵션을 제공합니다.

// Create MhtmlLoadOptions
MhtmlLoadOptions loadOptions = new MhtmlLoadOptions();

loadOptions.setPreferredTextEncoding(StandardCharsets.UTF_8);
loadOptions.setPreserveEmbeddedMessageFormat(true);
loadOptions.setPreserveTnefAttachments(true);
loadOptions.setRemoveSignature(false);

// Load the MHTML file
MailMessage mhtml = MailMessage.load("file.mht", loadOptions);

MhtmlLoadOptions 속성

  • MessageFormat - 메일 메시지 형식을 나타내며, EML, MSG 또는 MHTML이 될 수 있습니다. 기본값은 EML이며, Java에서는 읽기 전용 속성입니다.
  • PreferredTextEncoding - 메시지 제목과 본문의 선호 인코딩을 설정합니다. 기본값은 null.
  • PreserveEmbeddedMessageFormat - 임베디드 메시지 형식 보존 여부를 결정합니다. 기본값은 false.
  • PreserveTnefAttachments - TNEF 첨부 로딩 동작을 제어합니다. 기본값은 false.
  • RemoveSignature - 로드 중 서명을 제거할지 여부를 지정합니다. 기본값은 false.

MSG에서 로드

다음은 MsgLoadOptions 클래스는 MSG 파일 로드 방식을 다루는 여러 속성을 제공하며, RTF 내용 보존 또는 TNEF 첨부 관리 옵션을 포함합니다.

// Create MsgLoadOptions
MsgLoadOptions loadOptions = new MsgLoadOptions();

loadOptions.setKeepOriginalEmailAddresses(true);              // preserve the original email addresses
loadOptions.setPreferredTextEncoding(StandardCharsets.UTF_8);
loadOptions.setPreserveRtfContent(true);                      // keep the RTF content in the message
loadOptions.setPreserveTnefAttachments(true);
loadOptions.setRemoveSignature(false);
loadOptions.setTimeout(5000);                                 // limit the loading time to 5 seconds

// Load the MSG file
MailMessage msg = MailMessage.load("file.msg", loadOptions);

MsgLoadOptions 속성

  • KeepOriginalEmailAddresses - 원본 이메일 주소를 유지할지 여부를 나타냅니다. 기본값은 false.
  • PreferredTextEncoding - 메시지 제목 및 본문의 선호 인코딩을 정의합니다. 기본값은 null.
  • PreserveEmbeddedMessageFormat - 임베디드 메시지 형식 보존 여부를 결정합니다. 기본값은 false.
  • PreserveRtfContent - RTF 본문 내용을 MailMessage. 기본값은 false.
  • PreserveTnefAttachments - TNEF 첨부 로딩 동작을 관리합니다. 기본값은 false.
  • RemoveSignature - 로드 중 서명을 제거할지 결정합니다. 기본값은 false.
  • Timeout - 변환 중 포맷팅 시간을 밀리초 단위로 제한합니다. 기본값은 3000ms입니다.
  • TimeoutReachedHandler - 타임아웃이 만료될 때 발생하는 핸들러.

TNEF 로드

다음은 TnefLoadOptions 클래스는 TNEF 형식 EML 파일을 로드할 때 인코딩 관리 및 서명 제거 옵션을 제공합니다.

// Instantiate TnefLoadOptions
TnefLoadOptions loadOptions = new TnefLoadOptions();

loadOptions.setPreferredTextEncoding(StandardCharsets.UTF_8);
loadOptions.setPreserveEmbeddedMessageFormat(true);
loadOptions.setRemoveSignature(true);

// Load the TNEF file
MailMessage tnef = MailMessage.load("file.eml", loadOptions);

TnefLoadOptions 속성

  • MessageFormat - 메일 메시지 형식을 나타내며, EML, MSG 또는 MHTML 등입니다. 기본값은 EML이며, Java에서는 읽기 전용 속성입니다.
  • PreferredTextEncoding - 메시지 제목과 본문의 선호 인코딩을 설정합니다. 기본값은 null.
  • PreserveEmbeddedMessageFormat - 임베디드 메시지 형식을 보존할지 여부를 나타냅니다. 기본값은 false.
  • RemoveSignature - 로드 중 서명을 제거할지 여부를 지정합니다. 기본값은 false.

로드 중 임베디드 메시지 형식 보존

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

이메일 메시지 저장 및 변환

Aspose.Email를 사용하면 모든 메시지 유형을 다른 형식으로 쉽게 변환할 수 있습니다. 이 기능을 보여주기 위해 이 문서의 코드는 디스크에서 세 종류의 메시지를 로드하고 다른 형식으로 다시 저장합니다. 기본 클래스 SaveOptions 및 클래스 EmlSaveOptions, MsgSaveOptions, MhtSaveOptions, HtmlSaveOptions 저장 시 추가 설정을 위해 MailMessage 다른 형식으로 메시지를 저장하는 데 사용할 수 있습니다. 이 문서는 이러한 클래스를 사용하여 샘플 이메일을 다음과 같이 저장하는 방법을 보여줍니다:

  • EML 형식.
  • Outlook MSG.
  • MHTML 형식.
  • HTML 형식.

이메일 메시지 로드 및 저장

다음 코드 스니펫은 EML 메시지를 로드하고 동일한 형식으로 디스크에 저장하는 방법을 보여줍니다.

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

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

원본 메시지의 경계

EML 메시지를 로드하고 다시 EML로 저장하면 기본적으로 원본 메시지의 경계가 유지되므로 별도의 구성이 필요하지 않습니다. 이전 버전의 라이브러리에서는 EmlSaveOptions.PreserveOriginalBoundaries 이 용도로 사용되는 속성입니다. 해당 속성은 제거되었으며, 이제 원본 경계를 유지하는 것이 기본 동작입니다.

MIME 경계 사용자 지정

경계가 특정 패턴을 따라야 하는 경우 대신 다음을 사용하세요: BoundariesTemplate 속성 EmlSaveOptions 클래스입니다. 저장된 메시지의 MIME 경계를 생성하는 템플릿을 정의합니다. 기본값은 null, 이는 경계가 라이브러리에 의해 생성된다는 의미입니다. 템플릿에서는 두 개의 와일드카드가 지원됩니다:

  • {#} - 경계 번호.
  • {guid} - 생성된 GUID.

다음 코드 조각은 EML을 로드하고 사용자 지정 MIME 경계로 EML로 저장하는 방법을 보여줍니다.

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

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

// Save as EML with a custom boundary template
EmlSaveOptions emlSaveOptions = new EmlSaveOptions(MailMessageSaveType.getEmlFormat());
emlSaveOptions.setBoundariesTemplate("boundary_{#}_{guid}");

eml.save(dataDir + "CustomBoundaries_out.eml", emlSaveOptions);

TNEF 첨부 파일을 보존하며 EML로 저장

다음 코드 스니펫은 TNEF 첨부 파일을 보존하면서 EML로 저장하는 방법을 보여줍니다.

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

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

// Save as EML with the TNEF attachments preserved
EmlSaveOptions emlSaveOptions = new EmlSaveOptions(MailMessageSaveType.getEmlFormat());
emlSaveOptions.setFileCompatibilityMode(FileCompatibilityMode.PreserveTnefAttachments);

eml.save(dataDir + "PreserveTNEFAttachment_out.eml", emlSaveOptions);

EML을 MSG로 저장

다음 코드 스니펫은 적절한 옵션을 사용하여 EML 메시지를 로드하고 MSG로 변환하는 방법을 보여줍니다 SaveOptions.

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

// Initialize and load an existing EML file
MailMessage eml = MailMessage.load(dataDir + "test.eml");

// Save the email message to disk in Unicode format
eml.save(dataDir + "LoadingEMLSavingToMSG_out.msg", SaveOptions.getDefaultMsgUnicode());

날짜 보존하면서 EML을 MSG로 저장

다음은 MsgSaveOptions 클래스는 원본 메시지를 Outlook Message 파일(MSG)로 저장하면서 날짜를 보존합니다. 다음 코드 스니펫은 원본 날짜가 보존된 상태로 메시지를 MSG로 저장하는 방법을 보여줍니다.

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

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

// Save as MSG with the original dates preserved
MsgSaveOptions msgSaveOptions = new MsgSaveOptions(MailMessageSaveType.getOutlookMessageFormatUnicode());
msgSaveOptions.setPreserveOriginalDates(true);

eml.save(dataDir + "SavingAsMSGWithPreservedDates_out.msg", msgSaveOptions);

EML을 MHTML로 저장

원하는 결과를 얻기 위해 다양한 MHTML 옵션을 사용할 수 있습니다. 다음 코드 스니펫은 EML 메시지를 로드하는 방법을 보여줍니다: MailMessage 그리고 UTC 시스템의 메시지 날짜와 함께 MHTML로 변환합니다.

String dataDir = "data/";

// Set options for MHTML output
MhtSaveOptions saveOptions = SaveOptions.getDefaultMhtml();

// Save the message date as a UTC date
saveOptions.setPreserveOriginalDate(false);

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

EML 저장 시 MHT 헤더 전역 형식 지정

Aspose.Email를 사용하면 MHT 헤더에 대한 전역 형식 옵션을 사용할 수 있습니다. 전역 옵션은 모든 MHT 헤더에 공통 형식을 설정합니다. MhtSaveOptions 인스턴스. 이 기능은 각 인스턴스마다 형식을 설정하는 것을 방지하도록 설계되었습니다. MhtSaveOptions.

다음 메서드를 사용합니다: GlobalFormattingOptions 클래스와 아래 코드 샘플은 MHT 헤더의 형식을 설정합니다:

// The formatting is set once and applies to every MhtSaveOptions instance created afterwards
GlobalFormattingOptions.setPageHeaderFormat("<div><h1>{0}</h1></div>");
GlobalFormattingOptions.setHeaderFormat("<div>{0}: {1}</div>");
GlobalFormattingOptions.setBeforeHeadersFormat("<div style='font-family:Arial'>");
GlobalFormattingOptions.setAfterHeadersFormat("</div>");

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

옵션 설정으로 EML을 MHTML로 변환

다음은 MhtSaveOptions 이 클래스는 이메일 메시지를 MHTML 형식으로 저장하기 위한 추가 옵션을 제공합니다. 열거형 MhtFormatOptions 추가 이메일 정보를 출력 MHTML에 기록할 수 있게 합니다. 다음 추가 필드를 기록할 수 있습니다:

  • WriteHeader - 이메일 헤더를 출력 파일에 씁니다.
  • WriteOutlineAttachments - 개요 첨부 파일을 출력 파일에 씁니다.
  • WriteCompleteEmailAddress - 전체 이메일 주소를 출력 파일에 씁니다.
  • NoEncodeCharacters - 문자에 대한 전송 인코딩을 사용하지 않아야 합니다.
  • HideExtraPrintHeader - 출력 파일 상단의 추가 인쇄 헤더를 숨깁니다.
  • WriteCompleteToEmailAddress - 수신자의 전체 이메일 주소를 출력 파일에 씁니다.
  • WriteCompleteFromEmailAddress - 발신자의 전체 이메일 주소를 출력 파일에 씁니다.
  • WriteCompleteCcEmailAddress - 참조 수신자의 전체 이메일 주소를 출력 파일에 씁니다.
  • WriteCompleteBccEmailAddress - 숨은 참조 수신자의 전체 이메일 주소를 출력 파일에 씁니다.
  • RenderCalendarEvent - 캘린더 이벤트의 텍스트를 출력 파일에 씁니다.
  • SkipByteOrderMarkInBody - 메시지 본문에서 바이트 순서 표시(BOM) 바이트를 건너뜁니다.
  • RenderVCardInfo - VCard 대체 보기에 있는 텍스트를 출력 파일에 씁니다.
  • DisplayAsOutlook - From 헤더를 표시합니다.
  • RenderTaskFields - 특정 작업 필드를 출력 파일에 씁니다.
  • None - 지정된 설정이 없습니다.

다음 코드 스니펫은 선택적 설정을 사용하여 EML 파일을 MHTML로 변환하는 방법을 보여줍니다.

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

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

// Save as MHT with a header
MhtSaveOptions mhtSaveOptions = new MhtSaveOptions();
mhtSaveOptions.setMhtFormatOptions(MhtFormatOptions.WriteHeader | MhtFormatOptions.HideExtraPrintHeader);

eml.save(dataDir + "ConvertingToMHTMLWithOptionalSettings_out.mht", mhtSaveOptions);

MHTML로 변환하면서 캘린더 이벤트 렌더링

다음은 MhtFormatOptions.RenderCalendarEvent 옵션은 캘린더 이벤트를 출력 MHTML에 렌더링합니다. 다음 코드 스니펫은 MHTML로 변환하는 동안 캘린더 이벤트를 렌더링하는 방법을 보여줍니다.

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

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_Item overrides a template, and adds it when it is not in the collection yet.
options.getFormatTemplates().set_Item(MhtTemplateName.START,
        "<span class='headerLineTitle'>Start:</span><span class='headerLineText'>{0}</span><br/>");
options.getFormatTemplates().set_Item(MhtTemplateName.END,
        "<span class='headerLineTitle'>End:</span><span class='headerLineText'>{0}</span><br/>");
options.getFormatTemplates().set_Item(MhtTemplateName.RECURRENCE,
        "<span class='headerLineTitle'>Recurrence:</span><span class='headerLineText'>{0}</span><br/>");
options.getFormatTemplates().set_Item(MhtTemplateName.RECURRENCE_PATTERN,
        "<span class='headerLineTitle'>RecurrencePattern:</span><span class='headerLineText'>{0}</span><br/>");
options.getFormatTemplates().set_Item(MhtTemplateName.ORGANIZER,
        "<span class='headerLineTitle'>Organizer:</span><span class='headerLineText'>{0}</span><br/>");
options.getFormatTemplates().set_Item(MhtTemplateName.REQUIRED_ATTENDEES,
        "<span class='headerLineTitle'>RequiredAttendees:</span><span class='headerLineText'>{0}</span><br/>");

msg.save(dataDir + "Meeting with Recurring Occurrences_out.mhtml", options);

인라인 이미지 없이 이메일을 MHT로 내보내기

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

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

MhtSaveOptions mhtSaveOptions = new MhtSaveOptions();
mhtSaveOptions.setSkipInlineImages(true);

eml.save(dataDir + "EmlToMhtmlWithoutInlineImages_out.mht", mhtSaveOptions);

맞춤형 시간대로 이메일을 MHT로 내보내기

다음은 MailMessage class는 다음을 제공합니다 setTimeZoneOffset 메서드를 사용하여 MHT로 내보낼 때 사용자 정의 시간대를 설정합니다. 다음 코드 스니펫은 사용자 정의 시간대로 이메일을 MHT로 내보내는 방법을 보여줍니다.

String dataDir = "data/";

MailMessage msg = MailMessage.load(dataDir + "Message.msg", new MsgLoadOptions());
msg.setDate(new Date());

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

MhtSaveOptions mhtOptions = new MhtSaveOptions();
mhtOptions.setMhtFormatOptions(MhtFormatOptions.WriteHeader);

msg.save(dataDir + "ExportToMHTWithCustomTimezone_out.mhtml", mhtOptions);

이메일을 EML로 내보내기

다음 코드 스니펫은 이메일을 EML로 내보내는 방법을 보여줍니다.

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

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

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

이메일을 HTML로 저장

다음은 HtmlSaveOptions 클래스는 메시지 본문을 HTML로 내보내는 기능을 제공합니다. 다음 코드 스니펫은 메시지를 HTML로 저장하는 방법을 보여줍니다.

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

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.setHtmlFormatOptions(HtmlFormatOptions.WriteHeader | HtmlFormatOptions.WriteCompleteEmailAddress);

eml.save(dataDir + "SavingMessageAsHTML_out2.html", options);

리소스에 상대 경로를 사용하여 이메일 메시지를 HTML로 저장

이메일 메시지를 HTML 형식으로 내보낼 때 이메일 리소스를 상대 경로로 저장하도록 선택할 수 있습니다. 이 기능은 출력 HTML 파일에서 리소스가 연결되는 방식을 보다 유연하게 하여 다양한 시스템에서 저장된 이메일을 공유하고 표시하기 쉽게 합니다. HtmlSaveOptions.UseRelativePathToResources 속성은 리소스를 상대 경로로 저장할 수 있는 기능을 제공합니다. 기본값은 false(리소스가 절대 경로로 저장됨)입니다. true 로 설정하면 리소스가 상대 경로로 저장됩니다. 상대 경로를 사용하는 HTML 파일은 더 이식성이 높으며 호스팅 환경의 파일 구조와 관계없이 올바르게 표시됩니다. 절대 경로와 상대 경로 중 필요에 따라 선택할 수 있습니다. 또한 ResourceHtmlRenderingHandler 이벤트.

리소스를 기본 상대 경로로 저장

String dataDir = "data/";

MapiMessage msg = MapiMessage.load(dataDir + "message.msg");

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

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

이 경우 리소스는 [html file name].files 폴더에 저장되며, .html 파일과 동일한 경로에 있으며, HTML은 상대 경로를 통해 리소스를 참조합니다.

리소스에 절대 경로로 저장

String dataDir = "data/";

MapiMessage msg = MapiMessage.load(dataDir + "message.msg");

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

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

첫 번째 경우와 같이, 리소스는 [html file name].files 기본적으로 폴더에 저장되지만, HTML은 절대 경로를 사용하여 리소스를 참조합니다.

ResourceHtmlRenderingHandler 이벤트를 사용한 사용자 정의 상대 경로

String dataDir = "data/";

MapiMessage msg = MapiMessage.load(dataDir + "message.msg");

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

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

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

사용하여 ResourceHtmlRenderingHandler 이벤트를 사용하면 리소스에 대해 사용자 정의 상대 경로나 절대 경로를 설정할 수 있습니다. 경로를 사용자 정의할 때 ResourceHtmlRenderingHandler 이벤트 처리기에서, 상대 경로를 할당하십시오 PathToResourceFile 속성은 UseRelativePathToResources true 로 설정되고, false 일 때는 절대 경로가 지정되어 올바른 참조가 보장됩니다.

HTML로 변환하는 동안 메시지의 맞춤 아이콘 보존

때때로 메시지에 인라인 첨부 파일이 포함되어 메시지 본문에 아이콘 이미지로 표시됩니다. 이러한 메시지는 HTML로 변환할 때 아이콘 이미지가 손실되므로 문제가 발생할 수 있습니다. 이는 첨부 파일 아이콘이 메시지에 직접 포함되어 있지 않기 때문입니다.

Aspose.Email은 메시지를 HTML로 변환할 때 첨부 파일 아이콘을 사용자 지정할 수 있게 합니다. The ResourceHtmlRenderingHandler 이벤트는 이메일 메시지를 HTML 파일로 저장할 때 리소스 파일(예: 첨부 파일)의 렌더링을 사용자 정의하는 데 사용됩니다. 아래 코드 샘플에서 이벤트 핸들러는 첨부 파일의 콘텐츠 유형에 따라 리소스 파일(아이콘)의 경로를 동적으로 설정하는 데 사용됩니다. 이를 통해 파일 유형에 따라 HTML 출력에서 리소스를 맞춤 렌더링할 수 있습니다.

String dataDir = "data/";

HtmlSaveOptions options = new HtmlSaveOptions();

options.setResourceHtmlRenderingHandler(new ResourceHtmlRenderingHandler() {
    @Override
    public void invoke(Object sender, ResourceHtmlRenderingEventArgs e) {
        AttachmentBase attachment = (AttachmentBase) sender;
        String name = attachment.getContentType().getName();

        e.setCaption(name);

        if (name.endsWith(".pdf")) {
            e.setPathToResourceFile("pdf_icon.png");
        } else if (name.endsWith(".docx")) {
            e.setPathToResourceFile("word_icon.jpg");
        } else if (name.endsWith(".jpg")) {
            e.setPathToResourceFile("jpeg_icon.png");
        } else {
            e.setPathToResourceFile("not_found_icon.png");
        }
    }
});

options.setResourceRenderingMode(ResourceRenderingMode.SubstituteFromFile);

MailMessage mailMessage = MailMessage.load(dataDir + "message.msg");
mailMessage.save(dataDir + "message.html", options);

EML을 HTML로 저장할 때 시간 및 시간대 설정

Aspose.Email 사용자는 시간 및 시간대 표시 형식을 설정할 수 있습니다. HtmlSaveOptions. The HeadersFormattingOptions 클래스는 MailMessage를 MHTML 또는 HTML 형식으로 저장할 때 헤더 서식 옵션을 지정할 수 있게 합니다. 다음 상수는 HtmlFormatOptions 클래스는 출력 파일에 표시될 필드를 지정합니다:

  • RenderCalendarEvent - 캘린더 이벤트의 텍스트를 출력 HTML에 기록한다는 의미입니다.
  • RenderVCardInfo - VCard 대체 보기에 있는 텍스트를 출력 HTML에 기록한다는 의미입니다.

다음 코드 샘플은 EML을 HTML로 저장할 때 시간 및 시간대를 설정하는 방법을 보여줍니다:

String dataDir = "data/";

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

HtmlSaveOptions options = new HtmlSaveOptions();
options.setHtmlFormatOptions(HtmlFormatOptions.WriteHeader);
options.getFormatTemplates().set_Item(MhtTemplateName.DATE_TIME, "MM d yyyy HH:mm tt");

msg.save(dataDir + "Message_out.html", options);

리소스를 포함하지 않고 HTML로 저장

기본적으로 메시지 리소스는 data URI 형태로 출력 HTML에 포함됩니다. 설정 ResourceRenderingMode to ResourceRenderingMode.SaveToFile HTML 옆에 별도 파일로 저장하려면 이렇게 작성합니다.

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

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

HtmlSaveOptions options = new HtmlSaveOptions();

// Write the resources next to the HTML file instead of embedding them into it
options.setResourceRenderingMode(ResourceRenderingMode.SaveToFile);
options.setUseRelativePathToResources(true);

eml.save(dataDir + "EmailWithAttandEmbedded_out.html", options);

Outlook 템플릿(.oft) 파일로 메시지 저장

Outlook 템플릿은 MAPI 수준 형식이므로 메시지는 MapiMessage 먼저 저장한 뒤 다음과 같이 씁니다 saveAsTemplate. 다음 코드 스니펫은 Outlook 템플릿(.oft) 파일로 메시지를 저장하는 방법을 보여줍니다.

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

MailMessage eml = new MailMessage("test@from.to", "test@to.to", "template subject", "Template body");

// An Outlook template is a MAPI-level format, so convert the message first
MapiMessage msg = MapiMessage.fromMailMessage(eml);
msg.saveAsTemplate(dataDir + "EmlAsOft_out.oft");