Utility Features - MailMessage

Encrypting and Decrypting Messages

Aspose.Email provides facility to Encrypt and decrypt Email messages. This topic shows how an existing or new message can be loaded and encrypted using MailMessage. The encrypt() and decrypt() methods return the MailMessage object for the applied effects and needs to be taken care of while encrypting/decrypting messages. Encrypting and decrypting messages involves the following steps:

  1. Create a new message or load an existing one
  2. Encrypt the message using the certificate file
  3. Send the message or save it
  4. Decrypt the message as required

The following code snippet shows you how to encrypt and decrypt messages.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String publicCertFileName = dataDir + "MyKey.cer";
String privateCertFileName = dataDir + "MyPFX.pfx";
Path publicCertFilePath = Paths.get(publicCertFileName);
Path privateCertFilePath = Paths.get(privateCertFileName);
// Create a message
MailMessage msg = new MailMessage("atneostthaecrcount@gmail.com", "atneostthaecrcount@gmail.com", "Test subject", "Test Body");
// Encrypt the message
MailMessage eMsg = null;
try {
eMsg = msg.encrypt(Files.readAllBytes(publicCertFilePath), "");
if (eMsg.isEncrypted() == true)
System.out.println("Its encrypted");
else
System.out.println("Its NOT encrypted");
} catch (IOException e) {
e.printStackTrace();
}
// Decrypt the message
MailMessage dMsg = null;
try {
dMsg = eMsg.decrypt(Files.readAllBytes(privateCertFilePath), "password");
if (dMsg.isEncrypted() == true)
System.out.println("Its encrypted");
else
System.out.println("Its NOT encrypted");
} catch (IOException e) {
e.printStackTrace();
}

Checking a Message for Encryption

Aspose.Email MailMessage class allows checking a message if it is encrypted or not. The isEncrypted property of MailMessage allows checking this as shown in the following code sample.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Create a message
MailMessage originalMsg = MailMessage.load(dataDir + "Message.msg", new MsgLoadOptions());
if (originalMsg.isEncrypted() == true)
System.out.println("Its encrypted");
else
System.out.println("Its NOT encrypted");
// Encrypt the message
MailMessage mailMsg = null;
try {
mailMsg = originalMsg.encrypt(Files.readAllBytes(publicCertFilePath), "");
if (mailMsg.isEncrypted() == true)
System.out.println("Its encrypted");
else
System.out.println("Its NOT encrypted");
} catch (IOException e) {
e.printStackTrace();
}
// Decrypt the message
try {
mailMsg = mailMsg.decrypt(Files.readAllBytes(privateCertFilePath), "password");
if (mailMsg.isEncrypted() == true)
System.out.println("Its encrypted");
else
System.out.println("Its NOT encrypted");
} catch (IOException e) {
e.printStackTrace();
}

MailMessages Containing TNEF attachments

Transport Neutral Encapsulation Format (TNEF) is a proprietary email attachment format used by Microsoft Outlook and Microsoft Exchange Server. The Aspose.Email API allows you to read email messages that have TNEF attachments and modify the contents of them. The email can then be saved as a normal email or to the same format, preserving TNEF attachments. This article shows different code samples for working with messages containing TNEF attachments.

Reading Message by Preserving TNEF Attachments

The following code snippet shows you how to read a message by preserving TNEF attachments.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
EmlLoadOptions options = new EmlLoadOptions();
// This will Preserve the TNEF attachment as it is, file contains the TNEF attachment
options.setPreserveTnefAttachments(true);
MailMessage eml = MailMessage.load(dataDir + "tnefEml.eml", options);
for (Attachment attachment : eml.getAttachments())
{
System.out.println(attachment.getName());
}

Updating Resources in a TNEF Attachment and Preserving TNEF Format

The following code snippet shows you how to update resources in a TNEF attachment and preserve the TNEF format.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
public static void TestUpdateResources(String dataDir)
{
String fileName = dataDir + "tnefEMl1.eml";
String imgFileName = dataDir + "Untitled.jpg";
String outFileName = dataDir + "01_SAVE_Preserve_out.eml";
MailMessage originalMailMessage = MailMessage.load(fileName);
EmlLoadOptions emlOp = new EmlLoadOptions();
UpdateResources(originalMailMessage, imgFileName);
EmlSaveOptions emlSo = new EmlSaveOptions(MailMessageSaveType.getEmlFormat());
emlSo.setFileCompatibilityMode(FileCompatibilityMode.PreserveTnefAttachments);
originalMailMessage.save(outFileName, emlSo);
}
private static void UpdateResources(MailMessage msg, String imgFileName)
{
for (int i = 0; i < msg.getAttachments().size(); i++)
{
if (msg.getAttachments().get_Item(i).getContentType().getName().endsWith("jpg"))
{
try {
File attFile = new File(imgFileName);
msg.getAttachments().get_Item(i).setContentStream(new FileInputStream(attFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else if (msg.getAttachments().get_Item(i).getContentType().getName().endsWith("eml"))
{
ByteArrayOutputStream ms = new ByteArrayOutputStream();
msg.getAttachments().get_Item(i).save(ms);
//ms.reset();
ByteArrayInputStream ims = new ByteArrayInputStream(ms.toByteArray());
MailMessage embeddedMessage = MailMessage.load(ims);
UpdateResources(embeddedMessage, imgFileName);
ByteArrayOutputStream outProcessedEmbedded = new ByteArrayOutputStream();
embeddedMessage.save(outProcessedEmbedded, SaveOptions.getDefaultMsgUnicode());
//outProcessedEmbedded.reset();
ByteArrayInputStream inProcessedEmbedded = new ByteArrayInputStream(outProcessedEmbedded.toByteArray());
msg.getAttachments().get_Item(i).setContentStream(inProcessedEmbedded);
}
}
for (LinkedResource att : msg.getLinkedResources())
{
if (att.getContentType().getMediaType() == "image/jpg")
{
try {
File embeddedFile = new File(imgFileName);
FileInputStream es = null;
es = new FileInputStream(embeddedFile);
att.setContentStream(es );
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}

Adding New Attachments to Main Message Containing TNEF

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String fileName = "MainMessage.eml";
String attachName = "barcode.png";
String outFileName = "test_out.eml";
FileInputStream fi = new FileInputStream(dataDir + attachName);
MailMessage eml = MailMessage.load(dataDir + fileName);
eml.getAttachments().addItem(new Attachment(fi, "barcode.png", "image/png"));
eml.save(dataDir + outFileName);

Creating TNEF EML from MSG

Outlook MSGs sometimes contain information such as tables and text styles that may get disturbed if these are converted to EML. Creating TNEF messages from such MSG files allows us to retain the formatting and even send such messages via the email clients retaining the formatting. 

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MapiMessage msg = MapiMessage.fromFile(dataDir + "Message.msg");
MailConversionOptions options = new MailConversionOptions();
options.setConvertAsTnef (true);
MailMessage mail = msg.toMailMessage(options);

To create the TNEF, the following sample code can be used.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MsgLoadOptions msgLoadOptions = new MsgLoadOptions();
// The PreserveTnefAttachments option with MessageFormat.Msg will create the TNEF eml.
msgLoadOptions.setPreserveTnefAttachments(true);
MailMessage eml = MailMessage.load(dataDir + "test.eml", msgLoadOptions);

Detect if a Message is TNEF

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MailMessage mail = MailMessage.load(dataDir + "test.eml");
boolean isTnef = mail.getOriginalIsTnef();
System.out.println("isTnef: " + isTnef);

Processing of Bounced Messages

It is very common that a message sent to a recipient may bounce for any reason such as an invalid recipient address. Aspose.Email API has the capability to process such a message for checking if it is a bounced email or a regular email message. The CheckBounced method of the MailMessage class returns a valid result if the email message is a bounced email.

This article shows the usage of BounceResult class that provides the capability of checking if a message is a bounced email. It further gives detailed information about the recipients, action taken and the reason for the notification.

// 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(ProcessBouncedMessages.class) + "email/";
String fileName = "failed.msg";
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());
System.out.println();
fileName = "failed1.msg";
mail = MailMessage.load(dataDir + fileName);
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());
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();
fileName = "test.eml";
mail = MailMessage.load(dataDir + fileName);
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());

Bayesian Spam Analyzer

Aspose.Email provides the facility of e-mail filtering using the Bayes spam analyzer. It provides the SpamAnalyzer class for this purpose. This article shows how to train the filter to distinguish between the spam and regular emails based on the words database.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
public static void main(String[] args) {
// The path to the resource directory.
String dataDir = Utils.getSharedDataDir(BayesianSpamAnalyzer.class) + "email/";
SpamFilterTest(dataDir);
}
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);
java.io.File folder = new java.io.File(testFolder);
java.io.File[] testFiles = folder.listFiles();
SpamAnalyzer analyzer = new SpamAnalyzer(dataBaseFile);
for (int i = 0; i < testFiles.length; i++) {
MailMessage msg = MailMessage.load(testFiles[i].getAbsolutePath());
System.out.println(msg.getSubject());
double probability = analyzer.test(msg);
printResult(probability);
}
}
private static void teachAndCreateDatabase(String hamFolder, String spamFolder, String dataBaseFile) {
java.io.File folder = new java.io.File(hamFolder);
java.io.File[] hamFiles = folder.listFiles();
folder = new java.io.File(spamFolder);
java.io.File[] spamFiles = folder.listFiles();
SpamAnalyzer analyzer = new SpamAnalyzer();
for (int i = 0; i < hamFiles.length; i++) {
MailMessage hamMailMessage;
try {
hamMailMessage = MailMessage.load(hamFiles[i].getAbsolutePath());
} catch (Exception e) {
continue;
}
System.out.println(i);
analyzer.trainFilter(hamMailMessage, false);
}
for (int i = 0; i < spamFiles.length; i++) {
MailMessage spamMailMessage;
try {
spamMailMessage = MailMessage.load(spamFiles[i].getAbsolutePath());
} catch (Exception e) {
continue;
}
System.out.println(i);
analyzer.trainFilter(spamMailMessage, true);
}
analyzer.saveDatabase(dataBaseFile);
}
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)");
}