유틸리티 기능 - MailMessage
메시지 암호화 및 복호화
Aspose.Email는 이메일 메시지를 암호화 및 복호화하는 기능을 제공합니다. 이 항목에서는 기존 또는 새로운 메시지를 로드하고 다음을 사용하여 암호화하는 방법을 보여줍니다. MailMessage. The encrypt() 및 decrypt() 메서드는 적용된 효과에 대해 MailMessage 객체를 반환하며, 메시지를 암호화/복호화할 때 주의해야 합니다. 메시지 암호화 및 복호화는 다음 단계로 이루어집니다:
- 새 메시지를 만들거나 기존 메시지를 로드합니다
- 인증서 파일을 사용하여 메시지를 암호화합니다
- 메시지를 전송하거나 저장합니다
- 필요에 따라 메시지를 복호화합니다
다음 코드 스니펫은 메시지를 암호화 및 복호화하는 방법을 보여줍니다.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";
Path publicCertFilePath = Paths.get(dataDir + "MyKey.cer");
Path privateCertFilePath = Paths.get(dataDir + "MyPFX.pfx");
// Create a message
MailMessage msg = new MailMessage("sender@domain.com", "receiver@domain.com", "Test subject", "Test Body");
try {
// Encrypt the message with the public certificate
MailMessage encrypted = msg.encrypt(Files.readAllBytes(publicCertFilePath), "");
System.out.println("Encrypted: " + encrypted.isEncrypted());
// Decrypt it back with the private key and its password
MailMessage decrypted = encrypted.decrypt(Files.readAllBytes(privateCertFilePath), "password");
System.out.println("Encrypted: " + decrypted.isEncrypted());
} catch (IOException e) {
e.printStackTrace();
}
메시지 암호화 여부 확인
Aspose.Email MailMessage 클래스를 사용하면 메시지가 암호화되었는지 여부를 확인할 수 있습니다. isEncrypted MailMessage의 속성을 사용하면 아래 코드 샘플과 같이 이를 확인할 수 있습니다.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";
Path publicCertFilePath = Paths.get(dataDir + "MyKey.cer");
Path privateCertFilePath = Paths.get(dataDir + "MyPFX.pfx");
// Load a message and check whether it is already encrypted
MailMessage originalMsg = MailMessage.load(dataDir + "Message.msg", new MsgLoadOptions());
System.out.println("Encrypted: " + originalMsg.isEncrypted());
try {
// Encrypt the message
MailMessage mailMsg = originalMsg.encrypt(Files.readAllBytes(publicCertFilePath), "");
System.out.println("Encrypted: " + mailMsg.isEncrypted());
// Decrypt the message
mailMsg = mailMsg.decrypt(Files.readAllBytes(privateCertFilePath), "password");
System.out.println("Encrypted: " + mailMsg.isEncrypted());
} catch (IOException e) {
e.printStackTrace();
}
S/MIME 키를 사용한 메시지 서명 및 암호화
Aspose.Email for Java는 인증서(개인 키 포함 여부에 관계없이)를 SmimeKey. 별도의 X509Certificate2 Java API 유형: PFX, 개인 키 파일 또는 인증서 파일에서 키를 로드할 때는 SmimeKey의 정적 팩터리 메서드를 사용하고, 해당 객체를 서명 및 암호화 메서드에 전달합니다 MailMessage:
- loadPFX(String path, char[] password) - PFX 파일에서 개인 키와 인증서를 로드합니다. 비밀번호는
char[], PFX가 아니라String. - loadPrivateKey(String path) 및 loadCertificate(String path) - 개인 키나 인증서를 별도로 로드합니다.
- attachSignature(SmimeKey key) 및 attachDetachedSignature(SmimeKey key) - 메시지의 서명된 사본을 반환합니다.
- encrypt(SmimeKey… keys) 및 decrypt(SmimeKey key) - 하나 이상의 수신자를 위해 메시지를 암호화하고 다시 복호화합니다.
- checkSignatureCert() - 서명된 메시지의 서명 인증서를 반환합니다.
List<java.security.cert.X509Certificate>.
String dataDir = "data/";
MailMessage msg = new MailMessage("sender@domain.com", "receiver@domain.com", "Signed", "Body");
// A PFX holds the private key and its certificate; the password is a char array
SmimeKey key = SmimeKey.loadPFX(dataDir + "MyPFX.pfx", "password".toCharArray());
// Sign the message - pass true for a detached signature, or use attachDetachedSignature
MailMessage signed = msg.attachSignature(key);
// Encrypt with one or more recipient certificates
SmimeKey recipientCert = SmimeKey.loadCertificate(dataDir + "MyKey.cer");
MailMessage encrypted = signed.encrypt(recipientCert);
// Decrypt with the private key
MailMessage decrypted = encrypted.decrypt(key);
// Inspect the certificates of a signed message
for (java.security.cert.X509Certificate certificate : decrypted.checkSignatureCert()) {
System.out.println(certificate.getSubjectX500Principal());
}
Aspose.Email용 로케일 옵션 구성
다음을 사용할 수 있습니다 LocaleOptions 기본 로케일을 인식하지 못할 때 클래스를 사용하고 Aspose.Email 라이브러리에 가장 적합한 로케일을 설정합니다. 제공되는 메서드:
- getLocale() - Aspose.Email에서 사용하는 기본 로케일을 반환합니다.
- setLocale(Locale locale) 및 setLocale(String localeName) - Aspose.Email에서 사용하는 기본 로케일을 설정합니다.
- clear() - Aspose.Email의 기본 로케일을 해제하여 Java 기본 로케일을 다시 사용합니다.
다음 코드 샘플은 지정된 로케일 설정을 사용하여 파일에서 메일 메시지를 로드하는 방법을 보여줍니다:
final Locale locale = new Locale("en", "DE");
Locale.setDefault(locale);
// set Locale for Aspose Email lib
LocaleOptions.setLocale("en-US");
// or
//LocaleOptions.setLocale(new Locale("en", "US"));
MailMessage.load("document.msg");
이 코드는 애플리케이션과 Aspose.Email 라이브러리가 언어, 국가 및 문화 규약을 처리하기 위해 지정된 로케일을 사용하도록 보장합니다.
TNEF 첨부 파일이 포함된 MailMessage
Transport Neutral Encapsulation Format(TNEF)은 Microsoft Outlook 및 Microsoft Exchange Server에서 사용하는 독점 이메일 첨부 형식입니다. Aspose.Email API를 사용하면 TNEF 첨부 파일이 있는 이메일 메시지를 읽고 내용을 수정할 수 있습니다. 그런 이메일을 일반 이메일이나 동일한 형식으로 저장하면서 TNEF 첨부 파일을 보존할 수 있습니다. 이 문서에서는 TNEF 첨부 파일이 포함된 메시지를 다루는 다양한 코드 샘플을 보여줍니다.
TNEF 첨부 파일을 보존하며 메시지 읽기
다음 코드 스니펫은 TNEF 첨부 파일을 보존하면서 메시지를 읽는 방법을 보여줍니다.
// 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();
// This preserves the TNEF attachment as it is, if the file contains one
options.setPreserveTnefAttachments(true);
MailMessage eml = MailMessage.load(dataDir + "tnefEml.eml", options);
for (Attachment attachment : eml.getAttachments()) {
System.out.println(attachment.getName());
}
TNEF 첨부 파일의 리소스 업데이트 및 TNEF 형식 보존
다음 코드 스니펫은 TNEF 첨부 파일의 리소스를 업데이트하고 TNEF 형식을 보존하는 방법을 보여줍니다.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
public static void updateTnefResources(String dataDir) throws Exception {
String fileName = dataDir + "tnefEml.eml";
String imgFileName = dataDir + "Untitled.jpg";
String outFileName = dataDir + "01_SAVE_Preserve_out.eml";
MailMessage originalMailMessage = MailMessage.load(fileName);
updateResources(originalMailMessage, imgFileName);
EmlSaveOptions emlSaveOptions = new EmlSaveOptions(MailMessageSaveType.getEmlFormat());
emlSaveOptions.setFileCompatibilityMode(FileCompatibilityMode.PreserveTnefAttachments);
originalMailMessage.save(outFileName, emlSaveOptions);
}
private static void updateResources(MailMessage msg, String imgFileName) throws Exception {
for (int i = 0; i < msg.getAttachments().size(); i++) {
Attachment attachment = msg.getAttachments().get_Item(i);
String name = attachment.getContentType().getName();
if (name.endsWith("jpg")) {
attachment.setContentStream(new FileInputStream(imgFileName));
} else if (name.endsWith("eml")) {
// Replace the resources of the embedded message, then put it back
ByteArrayOutputStream embedded = new ByteArrayOutputStream();
attachment.save(embedded);
MailMessage embeddedMessage = MailMessage.load(new ByteArrayInputStream(embedded.toByteArray()));
updateResources(embeddedMessage, imgFileName);
ByteArrayOutputStream processed = new ByteArrayOutputStream();
embeddedMessage.save(processed, SaveOptions.getDefaultMsgUnicode());
attachment.setContentStream(new ByteArrayInputStream(processed.toByteArray()));
}
}
for (LinkedResource resource : msg.getLinkedResources()) {
// Compare the media type with equals: == compares references, not the text
if ("image/jpeg".equals(resource.getContentType().getMediaType())) {
resource.setContentStream(new FileInputStream(imgFileName));
}
}
}
TNEF가 포함된 메인 메시지에 새 첨부 파일 추가
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";
String fileName = "MainMessage.eml";
String attachName = "barcode.png";
String outFileName = "test_out.eml";
MailMessage eml = MailMessage.load(dataDir + fileName);
try (FileInputStream fi = new FileInputStream(dataDir + attachName)) {
eml.getAttachments().addItem(new Attachment(fi, attachName, "image/png"));
eml.save(dataDir + outFileName);
}
MSG에서 TNEF EML 만들기
Outlook MSG 파일에는 테이블 및 텍스트 스타일과 같은 정보가 포함되어 있어 EML로 변환하면 손상될 수 있습니다. 이러한 MSG 파일에서 TNEF 메시지를 생성하면 서식을 유지하고 이메일 클라이언트를 통해 서식을 유지한 채로 메시지를 보낼 수 있습니다.
// 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 + "Message.msg");
MailConversionOptions options = new MailConversionOptions();
options.setConvertAsTnef(true);
MailMessage mail = msg.toMailMessage(options);
TNEF를 생성하려면 다음 샘플 코드를 사용할 수 있습니다.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";
MsgLoadOptions msgLoadOptions = new MsgLoadOptions();
// The PreserveTnefAttachments option creates a TNEF EML out of an MSG file
msgLoadOptions.setPreserveTnefAttachments(true);
MailMessage eml = MailMessage.load(dataDir + "Message.msg", msgLoadOptions);
메시지가 TNEF인지 감지
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";
MailMessage mail = MailMessage.load(dataDir + "test.eml");
boolean isTnef = mail.getOriginalIsTnef();
System.out.println("isTnef: " + isTnef);
바운스 메시지 처리
받는 사람에게 보낸 메시지가 잘못된 주소와 같은 이유로 반송되는 경우는 매우 일반적입니다. Aspose.Email API는 이러한 메시지를 처리하여 반송된 이메일인지 일반 이메일인지 확인할 수 있는 기능을 제공합니다. The checkBounced 메서드 MailMessage 클래스는 이메일 메시지가 반송 메일인 경우 유효한 결과를 반환합니다.
이 문서는 다음의 사용법을 보여줍니다 BounceResult 클래스는 메시지가 반송 메일인지 여부를 보고하고, 수신자, 수행된 작업 및 알림 사유에 대한 자세한 정보를 제공합니다.
// 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/";
for (String fileName : new String[] { "failed.msg", "failed1.msg", "test.eml" }) {
MailMessage mail = MailMessage.load(dataDir + fileName);
BounceResult result = mail.checkBounced();
System.out.println(fileName);
System.out.println("IsBounced : " + result.isBounced());
System.out.println("Action : " + result.getAction());
System.out.println("Recipient : " + result.getRecipient());
if (result.isBounced()) {
System.out.println("Reason : " + result.getReason());
System.out.println("Status : " + result.getStatus());
System.out.println("OriginalMessage ToAddress 1: "
+ result.getOriginalMessage().getTo().get_Item(0).getAddress());
}
System.out.println();
}
예외 무시
이 라이브러리는 다음을 제공합니다 ExceptionManager 클래스를 사용하면 애플리케이션에서 선택된 예외를 무시하거나 모두 무시하거나 무시된 예외를 로그에 남길 수 있습니다. 자세히 보기 예외 무시 방법 자세한 내용 및 코드 샘플을 확인하십시오.
베이즈 스팸 분석기
Aspose.Email은 베이즈 스팸 분석기를 사용한 이메일 필터링 기능을 제공합니다. 이 기능은 SpamAnalyzer 이 목적을 위한 클래스. 이 문서는 단어 데이터베이스를 사용해 스팸을 일반 이메일과 구별하도록 필터를 학습시키는 방법을 보여줍니다.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
public static void spamFilterTest(String dataDir) {
String hamFolder = dataDir + "ham";
String spamFolder = dataDir + "spam";
String testFolder = dataDir + "test";
String databaseFile = dataDir + "SpamFilterDatabase.txt";
teachAndCreateDatabase(hamFolder, spamFolder, databaseFile);
SpamAnalyzer analyzer = new SpamAnalyzer(databaseFile);
for (File testFile : new File(testFolder).listFiles()) {
MailMessage msg = MailMessage.load(testFile.getAbsolutePath());
System.out.println(msg.getSubject());
printResult(analyzer.test(msg));
}
}
private static void teachAndCreateDatabase(String hamFolder, String spamFolder, String databaseFile) {
SpamAnalyzer analyzer = new SpamAnalyzer();
// Train on the known-good messages, then on the known-spam ones
train(analyzer, new File(hamFolder).listFiles(), false);
train(analyzer, new File(spamFolder).listFiles(), true);
analyzer.saveDatabase(databaseFile);
}
private static void train(SpamAnalyzer analyzer, File[] files, boolean isSpam) {
for (File file : files) {
try {
analyzer.trainFilter(MailMessage.load(file.getAbsolutePath()), isSpam);
} catch (RuntimeException e) {
// Skip the files that cannot be loaded as messages
}
}
}
private static void printResult(double probability) {
if (probability < 0.05) {
System.out.println("This is ham");
} else if (probability > 0.95) {
System.out.println("This is spam");
} else {
System.out.println("Maybe spam");
}
}
EML 메시지에서 프리앰블 및 에필로그 가져오기
MIME 형식에서 프리앰블은 헤더 뒤와 첫 번째 멀티파트 경계 앞에 나타나는 텍스트이며, 에필로그는 마지막 경계 뒤와 메시지 끝 사이에 나타나는 텍스트입니다. 이 텍스트는 일반 메일 리더에서 보이지 않지만, 일부 MIME 구현에서는 비 MIME 프로그램으로 읽는 수신자를 위해 메모를 삽입하는 데 사용합니다.
프리앰블과 에필로그는 해당 메서드로 읽고 쓸 수 있습니다 MailMessage 클래스:
- getPreamble() 및 setPreamble(String value) - 서문(프리앰블) 텍스트를 가져오거나 설정합니다.
- getEpilogue() 및 setEpilogue(String value) - 서문(에필로그) 텍스트를 가져오거나 설정합니다.
String dataDir = "data/";
MailMessage eml = MailMessage.load(dataDir + "message.eml");
// Read the preamble and the epilogue of the loaded message
System.out.println("Preamble: " + eml.getPreamble());
System.out.println("Epilogue: " + eml.getEpilogue());
// Both can be set before saving the message again
eml.setPreamble("This is a multi-part message in MIME format.");
eml.setEpilogue("End of the MIME message.");
eml.save(dataDir + "message_out.eml", SaveOptions.getDefaultEml());
MHT 파일에서 선택 참석자 표시
MHT 형식을 사용할 때, 캘린더 이벤트 헤더에서 선택 참석자 정보를 표시하거나 숨길 수 있습니다. 구성하려면 MhtSaveOptions MHT 파일 처리를 위해서는 MhtFormatOptions.RenderCalendarEvent 및 MhtFormatOptions.WriteHeader 값은 다음과 같이 작동합니다:
- MhtFormatOptions.RenderCalendarEvent - 캘린더 이벤트 상세 정보를 MHT 파일에 렌더링할지 제어합니다. 이 옵션을 설정하면 참석자 상세 정보를 포함한 종합적인 이벤트 정보가 출력에 포함됩니다.
- MhtFormatOptions.WriteHeader - 주제, 날짜 및 참가자 정보(구성된 경우 옵션 참석자 포함)와 같은 메타데이터가 포함된 헤더를 MHT 파일에 기록할지 여부를 결정합니다.
아래 코드 샘플은 MHTML 형식으로 메시지를 저장할 때 옵션 참석자 표시 기능을 사용하는 방법을 보여줍니다:
MhtSaveOptions options = new MhtSaveOptions();
options.setMhtFormatOptions(MhtFormatOptions.RenderCalendarEvent | MhtFormatOptions.WriteHeader);
MailMessage eml = MailMessage.load("meeting.msg");
eml.save("meeting.mhtml", options);
옵션 참석자 정보를 MHT 파일에서 제외하려면 저장 전에 옵션 참석자에 대한 형식 템플릿을 지우세요:
MhtSaveOptions options = new MhtSaveOptions();
options.setMhtFormatOptions(MhtFormatOptions.RenderCalendarEvent | MhtFormatOptions.WriteHeader);
// Skip the optional attendees in the MHTML output
options.getFormatTemplates().set_Item(MhtTemplateName.OPTIONAL_ATTENDEES, "");
MailMessage eml = MailMessage.load("meeting.msg");
eml.save("meeting2.mhtml", options);
MhtTemplateName.OPTIONAL_ATTENDEES 및 MhtTemplateName.REQUIRED_ATTENDEES템플릿 자체는 다음을 통해 설정됩니다: getFormatTemplates().set_Item(key, value).
MHTML에서 모든 헤더 저장
다음은 SaveAllHeaders 속성 MhtSaveOptions 클래스는 모든 헤더를 MHTML 출력에 쓸지 여부를 정의합니다. 다음 코드 스니펫은 메시지의 모든 헤더를 MHTML 파일에 저장하는 방법을 보여줍니다:
MailMessage eml = MailMessage.load("message.eml");
MhtSaveOptions sopt = SaveOptions.getDefaultMhtml();
sopt.setSaveAllHeaders(true);
eml.save("message.mhtml", sopt);
MDN 및 읽음 확인을 이용한 이메일 추적
Aspose.Email API는 메시지 배달 확인(MDN)을 사용한 이메일 추적을 지원합니다. 이는 읽음 확인을 요청하고 필요한 정보를 생성함으로써 구현됩니다:
MailMessage.setReadReceiptTo(MailAddressCollection)읽음 확인 주소를 설정합니다.MailMessage.createReadReceipt(String, String)수신 메시지에 대한 읽음 확인을 빌드합니다.MapiMessage.setReadReceiptRequested(boolean)Outlook 메시지에 대해 읽음 확인 요청 여부를 설정합니다.
다음 코드 스니펫은 Aspose.Email API를 사용해 이메일을 추적하는 방법을 보여줍니다:
try (SmtpClient client = new SmtpClient("smtp.server.com", 587, "username", "password")) {
// Send a message with a requested read receipt
MailMessage mailMessage = new MailMessage("from@domain.com", "to@domain.com",
"test MDN", "This is a test message with read receipt requested");
MailAddressCollection readReceiptTo = new MailAddressCollection();
readReceiptTo.add("from@domain.com");
readReceiptTo.add("another@domain.com");
mailMessage.setReadReceiptTo(readReceiptTo);
client.send(mailMessage);
// On the recipient side: check the request, then create and send the read receipt
MailMessage emlMDN = MailMessage.load("received.eml");
if (emlMDN.getReadReceiptTo().size() > 0) {
client.send(emlMDN.createReadReceipt("to@domain.com", null));
}
}
읽음 확인은 Outlook 메시지에서도 요청할 수 있습니다:
// Create a MapiMessage with a requested read receipt
MapiMessage mapiMessage = new MapiMessage("from@domain.com", "to@domain.com",
"test MDN", "This is a read requested mapiMessage", OutlookMessageFormat.Unicode);
mapiMessage.setReadReceiptRequested(true);
// Or create a MailMessage with a requested read receipt and convert it to a MapiMessage
MailMessage mailMessage = new MailMessage("from@domain.com", "to@domain.com",
"test MDN", "This is a test message with read receipt requested");
MailAddressCollection readReceiptTo = new MailAddressCollection();
readReceiptTo.add("from@domain.com");
mailMessage.setReadReceiptTo(readReceiptTo);
MapiMessage converted = MapiMessage.fromMailMessage(mailMessage, MapiConversionOptions.getUnicodeFormat());
setReadReceiptTo Aspose.Email for Java에서는 MailAddressCollection — 단일 주소라도 먼저 컬렉션을 구축합니다.