메시지 첨부 파일 작업
첨부 파일 파싱 및 저장
Outlook 메시지 파일에는 하나 이상 첨부 파일이 포함될 수 있습니다. Aspose.Email을 사용하면 개발자가 MSG 파일의 첨부 파일을 순회하여 디스크에 저장할 수 있습니다. 이 항목에서는 그 과정을 설명하고 첨부 파일을 삽입하는 방법도 다룹니다.
Aspose.Email MapiMessage 클래스는 디스크에서 MSG 파일을 로드하고 다음을 노출합니다. getAttachments() 참조하는 메서드 MapiAttachment MSG 파일과 연관된 객체 컬렉션. 해당 MapiAttachment 객체는 첨부 파일에 대한 작업을 수행하는 메서드를 추가로 제공합니다.
원본 이름과 확장자를 유지하여 MSG 파일의 첨부 파일을 디스크에 저장하려면:
- 다음의 인스턴스를 생성합니다. MapiMessage 클래스는 다음을 사용하여 MSG 파일을 로드합니다 Load() 정적 메서드.
- 다음을 호출합니다. MapiRecipient 클래스 getAttachments() 컬렉션에 대한 참조를 얻는 메서드 MapiAttachment MSG 파일과 연관된 객체들.
- 반복합니다 MapiAttachmentCollection 각 항목에 대한 내용을 표시하려면 MapiAttachment 객체를 공개 메서드를 통해 사용합니다.
- 다음을 호출합니다. MapiAttachment 클래스 save() 첨부 파일을 디스크에 저장하는 메서드.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";
// Load an MSG file from disk
MapiMessage outlookMessageFile = MapiMessage.load(dataDir + "WithEmbeddedMsg.msg");
// Loop through the attachments collection of the MapiMessage object
for (MapiAttachment attachment : outlookMessageFile.getAttachments()) {
// Display the attachment type
System.out.println("Att Type : " + attachment.getMimeTag());
// Display the attached file name
System.out.println("File Name : " + attachment.getLongFileName());
// Save the attachment to disk
attachment.save(dataDir + attachment.getDisplayName());
}
첨부 파일로 메시지 삽입
Microsoft Outlook 메시지는 첨부 파일로 다른 Outlook 메시지를 일반 메시지(위에 설명) 또는 삽입된 메시지 형태로 포함할 수 있습니다. 해당 MapiAttachmentCollection add 메서드의 오버로드된 멤버를 제공하여 두 종류의 첨부 파일을 가진 Outlook 메시지를 생성합니다. Outlook MSG 파일에 포함된 MSG 파일은 값이 5인 PR_ATTACH_METHOD를 포함합니다.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";
MapiMessage msg = new MapiMessage("from@test.com", "to@test.com", "Subj", "This is a message body");
MapiMessage attachMsg = MapiMessage.load(dataDir + "message.msg");
msg.getAttachments().add("Weekly report", attachMsg);
msg.save(dataDir + "EmbeddedMessageAsAttachment.msg");
첨부 파일에서 삽입된 메시지 읽기
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";
MapiMessage mapi = MapiMessage.load(dataDir + "EmbeddedMessageAsAttachment.msg");
MapiMessage embedded = mapi.getAttachments().get_Item(0).getObjectData().toMapiMessage();
System.out.println("Embedded subject: " + embedded.getSubject());
MSG 첨부 파일 추가
Outlook 메시지는 첨부 파일로 다른 Microsoft Outlook 메시지를 포함할 수 있으며, 일반 메시지나 임베디드 메시지로 포함될 수 있습니다. 해당 MapiAttachmentCollection 다음의 오버로드된 멤버를 제공합니다 add 두 종류의 첨부 파일을 모두 포함한 Outlook 메시지를 만드는 메서드:
add(String name, byte[] data)— 바이트 배열에서 일반 첨부 파일을 추가합니다.add(String name, MapiMessage message)— 다른 Outlook 메시지를 임베디드 메시지로 추가합니다.
다음 코드 조각은 메시지에 두 종류의 첨부 파일을 모두 추가하는 방법을 보여줍니다:
MapiMessage message = new MapiMessage("from@test.com", "to@test.com", "Subj", "This is a message body");
// Add a regular attachment from a byte array
message.getAttachments().add("note.txt", Files.readAllBytes(Paths.get("note.txt")));
// Add another Outlook message as an embedded message
MapiMessage attachMsg = MapiMessage.load("Message.msg");
message.getAttachments().add("Weekly report.msg", attachMsg);
message.save("WithAttachments_out.msg");
MapiMessage.fromFile Aspose.Email for Java에는 존재하지 않습니다 — 대신 MapiMessage.load 디스크에서 MSG 파일을 읽는 방법.
새로 추가된 첨부 파일에 접근
다음은 add 의 메서드 MapiAttachmentCollection 클래스는 반환합니다 MapiAttachment 그들이 생성하는 객체. 이렇게 하면 새 첨부 파일에 즉시 접근할 수 있어 삽입 직후 컬렉션을 검색하지 않고도 구성할 수 있습니다. 다음 오버로드는 생성된 첨부 파일을 반환합니다:
- add(String name, byte[] data)
- add(String name, MapiMessage msg)
- add(String name, ReferenceAttachmentOptions options)
다음 코드 스니펫은 첨부 파일을 추가하고 표시 이름을 변경합니다:
MapiMessage message = new MapiMessage("from@domain.com", "to@domain.com", "Invoice", "Please find the invoice attached.");
MapiAttachment attachment = message.getAttachments().add("invoice.pdf", Files.readAllBytes(Paths.get("invoice.pdf")));
attachment.setDisplayName("Invoice #2026-001.pdf");
message.save("invoice.msg");
스트림 또는 파일에서 첨부 파일 추가
첨부 파일이 바이트 배열에서 추가될 경우 전체 내용을 메모리에 보관해야 합니다. 큰 파일의 경우 스트림으로 내용을 공급하거나 파일에서 직접 가져오세요: 내용은 저장 중에 필요에 따라 읽히며 전체가 메모리로 복사되지 않습니다. 그 MapiAttachmentCollection 클래스는 이를 위한 다음 메서드를 제공합니다:
- add(String name, InputStream content) - 스트림의 현재 위치부터 끝까지 읽은 내용으로 첨부 파일을 추가합니다. 스트림은 귀하가 제어하며 메시지가 저장될 때까지 열려 있어야 합니다.
addFile(String filePath)- 파일에서 첨부 파일을 추가하고 파일 이름을 첨부 파일 이름으로 사용합니다.addFile(String filePath, String displayName)- 지정된 표시 이름을 사용하여 파일에서 첨부 파일을 추가합니다.
이러한 모든 메서드는 생성된 MapiAttachment 객체. 그 getContentLength() 메서드는 첨부 파일 내용을 읽지 않고 바이트 단위 크기를 반환합니다.
다음 코드 조각은 큰 파일을 첨부합니다. 내용은 메시지를 저장하는 동안 파일에서 읽히므로, 더 이상 필요하지 않을 때 메시지를 폐기하십시오 - try-with-resources 구문이 이를 수행합니다:
try (MapiMessage msg = new MapiMessage("from@domain.com", "to@domain.com", "Quarterly report", "See the archive attached.")) {
msg.getAttachments().addFile("archive.zip");
msg.save("report.msg");
}
다음 코드 조각은 기존 스트림에서 첨부 파일을 추가하고 크기를 출력합니다:
try (InputStream content = Files.newInputStream(Paths.get("presentation.pptx"))) {
MapiMessage msg = new MapiMessage("from@domain.com", "to@domain.com", "Slides", "Slides attached.");
MapiAttachment attachment = msg.getAttachments().add("presentation.pptx", content);
// The size is known without reading the content
System.out.println("Attachment size: " + attachment.getContentLength() + " bytes");
// The stream must stay open until the message is saved
msg.save("slides.msg");
}
스트림으로 첨부 파일 콘텐츠 읽기
다음은 openRead() 메서드 MapiAttachment 클래스는 첨부 파일 내용에 대한 읽기 전용 스트림을 반환합니다. 이를 사용해 큰 첨부 파일을 바이트 배열로 변환하지 않고 복사하거나 처리할 수 있습니다. 각 호출은 별개의 독립된 스트림을 반환하므로 여러 리더를 동시에 사용할 수 있습니다.
MapiMessage msg = MapiMessage.load("message.msg");
for (MapiAttachment attachment : msg.getAttachments()) {
System.out.println(attachment.getLongFileName() + " : " + attachment.getContentLength() + " bytes");
// Stream the content to a file instead of reading it into a byte array
try (InputStream source = attachment.openRead()) {
Files.copy(source, Paths.get("out", attachment.getLongFileName()), StandardCopyOption.REPLACE_EXISTING);
}
}
첨부 파일 내용을 전혀 읽지 않고 메시지를 열려면, 다음에 설명된 지연 첨부 파일 로딩을 사용하십시오 MSG 파일 로드, 보기 및 구문 분석.
MapiMessages에 참조 첨부 파일 추가
다음은 ReferenceAttachmentOptions 클래스는 모든 필요한 속성을 단일 객체에 캡슐화하여 참조 첨부 파일 추가를 단순화합니다:
- sharedLink — 파일을 호스팅하는 웹 서비스가 제공하는 완전한 공유 링크;
- url — 파일 위치 또는 리소스 URL;
- providerName — 참조 첨부 파일 제공자의 이름(예: Google Drive, Dropbox).
MapiMessage msg = MapiMessage.load("message.msg");
ReferenceAttachmentOptions options = new ReferenceAttachmentOptions(
"https://drive.google.com/file/d/1HJ-M3F2qq1oRrTZ2GZhUdErJNy2CT3DF/",
"https://drive.google.com/drive/my-drive",
"GoogleDrive");
// Add the reference attachment
msg.getAttachments().add("Document.pdf", options);
msg.save("with-reference-attachment.msg");
첨부 파일 유형 확인 (IsReference)
다음은 MapiAttachment 클래스는 isReference() 메서드에 나타나며, 개발자가 메시지에서 참조 첨부 파일을 식별할 수 있게 합니다:
MapiMessage msg = MapiMessage.load("message.msg");
for (MapiAttachment attachment : msg.getAttachments()) {
if (attachment.isReference()) {
// Process the reference attachment
System.out.println("Reference attachment: " + attachment.getLongFileName());
}
}
중첩 메일 메시지 첨부 파일 가져오기
임베디드 메시지 첨부 파일은 또한 MapiMessage 클래스. MapiMessage.fromProperties() 정적 메서드는 임베디드 첨부 파일에서 새 메시지를 생성합니다. 다음 코드 샘플은 중첩된 메일 메시지 첨부 파일을 가져와 디스크에 저장하는 방법을 보여줍니다:
MapiMessage msg = MapiMessage.load("message.msg");
for (MapiAttachment attachment : msg.getAttachments()) {
if (attachment.getObjectData() == null) {
continue;
}
// Create a MapiMessage object from the individual attachment
MapiMessage nested = MapiMessage.fromProperties(attachment.getObjectData().getProperties());
// Convert the embedded message to a MailMessage and save it to disk
MailMessage mailMessage = nested.toMailMessage(new MailConversionOptions());
mailMessage.save("NestedMailMessageAttachments_out.eml", SaveOptions.getDefaultEml());
}
첨부 파일 제거
Aspose.Email은 Microsoft Outlook 메시지(.msg) 파일에서 첨부 파일을 제거하는 기능을 제공합니다. 정적 removeAttachments() 메서드를 호출할 수 있으며, 여기서는 메시지 파일 경로를 매개변수로 받습니다:
MapiMessage.removeAttachments("AttachmentsToRemove_out.msg");
또한 정적 destroyAttachments() 메서드. 이 메서드는 removeAttachments(), 왜냐하면 후자는 메시지 파일을 파싱하기 때문입니다:
MapiMessage.destroyAttachments("AttachmentsToDestroy_out.msg");
첨부 파일 MSG 삽입 및 교체
Aspose.Email API는 부모 메시지의 특정 인덱스에 첨부 파일을 삽입할 수 있는 기능을 제공합니다. 또한 한 첨부 파일의 내용을 다른 메시지 첨부 파일로 교체하는 기능도 제공합니다.
특정 위치에 MSG 첨부 파일 삽입
Aspose.Email API는 부모 MSG에 MSG 첨부 파일을 삽입하는 기능을 제공합니다. MapiAttachmentCollection.Insert() 메서드.
// 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 + "WithEmbeddedMsg.msg");
msg.getAttachments().get_Item(0).save(dataDir + "attachment_out.msg");
MapiMessage emb = MapiMessage.load(dataDir + "WithEmbeddedMsg.msg");
// Insert the message as the attachment at index 1
msg.getAttachments().insert(1, "new 11", emb);
msg.save(dataDir + "insertMSGAttachment_out.msg");
삽입된 MSG 첨부 파일 내용 교체
이를 사용하여 삽입된 첨부 파일 내용을 새로운 것으로 교체할 수 있습니다. 교체 메서드. 그러나 컬렉션.Count = 2인 경우 PR_ATTACH_NUM = 4(예시) 인 첨부 파일을 삽입하는 데는 사용할 수 없습니다.
// 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 + "insertMSGAttachment_out.msg");
msg.getAttachments().get_Item(0).save(dataDir + "attachment_out.msg");
MapiMessage emb = MapiMessage.load(dataDir + "insertMSGAttachment_out.msg");
// Replace the contents of the attachment at index 1
msg.getAttachments().replace(1, "new 1", emb);
msg.save(dataDir + "replaceEmbeddedMSGAttachment_out.msg");
디지털 서명된 메시지에서 첨부 파일 저장
Aspose.Email API는 클리어 서명된 메시지를 디코딩할지 여부를 나타내는 값을 가져오거나 설정하는 기능을 제공합니다.
String dataDir = "data/";
MapiMessage msg = MapiMessage.load(dataDir + "signed.msg");
// The attachments of a clear-signed message are wrapped in the signature,
// so remove it first and read the attachments from the resulting message
if (msg.isSigned()) {
SmimeResult result = new SecureEmailManager().checkSignature(msg);
System.out.println("Signature valid: " + result.isSuccess());
msg = msg.removeSignature();
}
for (MapiAttachment attachment : msg.getAttachments()) {
System.out.println(attachment.getLongFileName());
attachment.save(dataDir + attachment.getLongFileName());
}
MapiMessage에서 첨부 파일 이름 바꾸기
Aspose.Email을 사용하면 다음을 편집할 수 있습니다 표시 이름 속성 값 MapiMessage 첨부 파일.
다음 코드 샘플은 로드된 Mapi 메시지에서 첫 번째와 두 번째 첨부 파일의 표시 이름을 업데이트하는 방법을 보여줍니다.
MapiMessage msg = MapiMessage.load(fileName);
msg.getAttachments().get_Item(0).setDisplayName("New display name 1");
msg.getAttachments().get_Item(1).setDisplayName("New display name 2");
첨부 파일이 인라인인지 일반인지 확인
인라인 첨부 파일과 일반 첨부 파일의 차이는 이메일 내에서 표시되는 방식입니다. 인라인 첨부 파일은 이메일 본문에 삽입되어 별도의 파일을 열거나 다운로드하지 않아도 볼 수 있습니다. 반면 일반 첨부 파일은 이메일에 첨부된 별도의 파일이며 본문에 직접 표시되지 않아 다운로드 후 외부에서 열어야 합니다. 해당 MapiAttachment.IsInline 속성 MapiAttachment 클래스는 첨부 파일이 인라인인지 일반인지 나타내는 값을 가져옵니다.
다음 코드 샘플은 파일에서 이메일 메시지를 로드한 뒤 첨부 파일 정보를 가져옵니다. 특히 각 첨부 파일의 표시 이름과 메시지 내에 인라인인지 여부를 출력합니다.
MapiMessage message = MapiMessage.load("fileName");
for (MapiAttachment attach : message.getAttachments()) {
System.out.println(attach.getDisplayName() + ": " + attach.isInline());
}
oledata.mso에서 포함된 OLE 객체 추출
때때로 포함된 OLE 데이터가 oledata.mso 첨부 파일을 MapiAttachment 와 같은 오픈소스 라이브러리와 함께 사용할 수 있습니다. 이러한 파일은 수동으로 추출해야 합니다. oledata.mso 파일은 Microsoft 복합 문서 파일(MCDF) 형식이며, 이러한 파일에 대한 지원은 Aspose.Email 범위를 벗어납니다. 그러나 Aspose.Email은 InlineAttachmentExtractor MSO 패키지를 열거하는 클래스: oledata.mso, 이를 복합 파일 읽기 라이브러리에 전달할 수 있습니다(예: Apache POI POIFS)를 사용하여 콘텐츠를 추출합니다.
메시지 본문 형식이 HTML(RTF가 아님)이고 메시지에 OLE 객체가 포함된 경우 MapiPropertyTag.PR_ATTACH_DATA_OBJ 속성이 없습니다. 이 경우 OLE 객체에 대한 정보가 oledata.mso.
아래 코드는 MSO 패키지를 열거하고 각각을 별도 파일에 기록하여 복합 파일 리더로 열 수 있게 합니다:
MapiMessage msg = MapiMessage.load("double.msg");
for (MapiAttachment mapiAttachment : msg.getAttachments()) {
if (!"oledata.mso".equals(mapiAttachment.getLongFileName())) {
continue;
}
com.aspose.email.system.collections.generic.IGenericDictionary<String, byte[]> oledata =
InlineAttachmentExtractor.enumerateMsoPackage(new ByteArrayInputStream(mapiAttachment.getBinaryData()));
int index = 0;
for (com.aspose.email.system.collections.generic.KeyValuePair<String, byte[]> oleItem : oledata) {
// Each value is a compound file - read its CONTENTS stream with an MCDF library,
// or store it as is for further processing
Files.write(Paths.get(index + ".mso"), oleItem.getValue());
index++;
}
}