คุณสมบัติเครื่องมือ - MailMessage
การเข้ารหัสและถอดรหัสข้อความ
Aspose.Email มีฟีเจอร์เพื่อเข้ารหัสและถอดรหัสข้อความอีเมล หัวข้อนี้แสดงวิธีโหลดและเข้ารหัสข้อความที่มีอยู่หรือใหม่โดยใช้ MailMessage. ส่วน 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 สำหรับ Java แทนที่ใบรับรอง, มีหรือไม่มีคีย์ส่วนตัว, ด้วย SmimeKey. ไม่มี X509Certificate2 ชนิดใน Java API: คีย์จะโหลดจาก PFX, ไฟล์คีย์ส่วนตัวหรือไฟล์ใบรับรองด้วยเมธอดสเตติกของ SmimeKey แล้วส่งออบเจกต์ไปยังเมธอดเซ็นและเข้ารหัสของ MailMessage:
- loadPFX(String path, char[] password) - โหลดคีย์ส่วนตัวและใบรับรองจากไฟล์ PFX หมายเหตุว่ารหัสดังกล่าวเป็น
char[], ไม่ใช่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());
}
กำหนดค่าตัวเลือก Locale สำหรับ Aspose.Email
คุณสามารถใช้ LocaleOptions คลาสเมื่อ locale เริ่มต้นไม่รู้จัก และตั้ง locale ที่เหมาะสมที่สุดสำหรับไลบรารี Aspose.Email มีเมธอดต่อไปนี้:
- getLocale() - คืนค่า locale เริ่มต้นที่ใช้โดย Aspose.Email
- setLocale(Locale locale) และ setLocale(String localeName) - ตั้ง locale เริ่มต้นที่ใช้โดย Aspose.Email
- clear() - ล้าง locale เริ่มต้นของ Aspose.Email เพื่อให้ locale เริ่มต้นของ Java ถูกใช้อีกครั้ง
ตัวอย่างโค้ดต่อไปนี้แสดงวิธีโหลดข้อความเมลจากไฟล์โดยใช้การตั้งค่า locale ที่ระบุ:
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 ใช้ locale ที่ระบุสำหรับการจัดการภาษา ประเทศ และขนบธรรมเนียมวัฒนธรรม
ข้อความอีเมลที่มีไฟล์แนบ TNEF
Transport Neutral Encapsulation Format (TNEF) เป็นรูปแบบไฟล์แนบอีเมลที่เป็นกรรมสิทธิ์ใช้โดย Microsoft Outlook และ Microsoft Exchange Server API ของ Aspose.Email อนุญาตให้คุณอ่านข้อความอีเมลที่มีไฟล์แนบ 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);
}
สร้าง TNEF EML จาก MSG
ไฟล์ MSG ของ Outlook บางครั้งมีข้อมูลเช่นตารางและสไตล์ข้อความที่อาจเสียหายหากแปลงเป็น EML การสร้างข้อความ TNEF จากไฟล์ MSG ดังกล่าวทำให้เรารักษาการจัดรูปแบบและแม้กระทั่งส่งข้อความเหล่านี้ผ่านไคลเอนต์อีเมลโดยคงรูปแบบเดิม.
// 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 คลาสจะคืนผลลัพธ์ที่ถูกต้องหากข้อความอีเมลเป็น bounced email.
บทความนี้แสดงการใช้ 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 มีฟีเจอร์การกรองอีเมลด้วย Bayesian spam analyzer ให้ 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, preamble คือข้อความที่อยู่หลังส่วนหัวและก่อนขอบเขต multipart แรก epilogue คือข้อความที่อยู่หลังขอบเขตสุดท้ายและก่อนจบข้อความ ข้อความนี้มักไม่ปรากฏต่อผู้ใช้ในโปรแกรมอ่านเมล แต่บางการทำงานของ MIME จะใช้เพื่อใส่บันทึกให้ผู้รับที่อ่านด้วยโปรแกรมที่ไม่รองรับ MIME
preamble และ epilogue ถูกอ่านและเขียนด้วยเมธอดที่สอดคล้องของ MailMessage คลาส:
- getPreamble() และ setPreamble(String value) - รับหรือกำหนดข้อความ preamble
- getEpilogue() และ setEpilogue(String value) - รับหรือกำหนดข้อความ epilogue
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 หรือไม่
ตัวอย่างโค้ดด้านล่างแสดงวิธีใช้ฟีเจอร์ display optional attendees เมื่อบันทึกข้อความในรูปแบบ 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 ให้การสนับสนุนการติดตามอีเมลโดยใช้ Message Disposition Notification (MDN) ซึ่งทำได้โดยการขอการรับรู้การอ่านและสร้างข้อมูลที่จำเป็น:
MailMessage.setReadReceiptTo(MailAddressCollection)ตั้งค่าที่อยู่การรับรู้การอ่านMailMessage.createReadReceipt(String, String)สร้างการรับรู้การอ่านสำหรับข้อความที่ได้รับMapiMessage.setReadReceiptRequested(boolean)กำหนดว่าข้อความ Outlook จะขอการรับรู้การอ่านหรือไม่
ตัวอย่างโค้ดต่อไปนี้แสดงวิธีติดตามอีเมลด้วย API ของ Aspose.Email:
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 — สร้างคอลเล็กชันก่อนแม้จะเป็นที่อยู่เดียว